Manish
Manish

Reputation: 539

TextInput to accept numbers, along with commas and decimal values

I wish to implement a TextInput such that it accepts the amount of money in different possible formats.

For example:

250

2,50,000

2.50

Let's say I type in 2f50, it should be 250. If we type 2.5, it should remain 2.5 and for 2,50,000; it's 2,50,000 only.

My TextInput should accept only numbers, commas, and decimals only.

Upvotes: 0

Views: 162

Answers (1)

Ahmed Sbai
Ahmed Sbai

Reputation: 16249

var ah = '.45f,,6f7..'
var i = ah.length - 1;

while (i != 0) { 
 if (
   (isNaN(ah[i])  && ah[i] != "." && ah[i] != ",") ||
   ((ah[i] == "," || ah[i] == ".") && (ah[i - 1] == "," || ah[i - 1] == "."))
 ) {
   ah = ah.slice(0, i) + ah.slice(i + 1);
  }
 i--;
 }

if (ah.includes(".") && ah.includes(",")) ah = ah.replace(/,/g, ".");

When the user finishes typing ie when you want to use your input value

  1. you check if the input value endswith . or , so you remove it
if (ah.endsWith(".") || ah.endsWith(","))
      ah = ah.slice(0, ah.length - 1) + ah.slice(ah.length);
  1. you check if the input value startswith . or , so you remove it ( I dont know if you want do this but this is how )
if (ah.startsWith(".") || ah.startsWith(","))
       ah = ah.slice(1, ah.length) 

Note : these tests should not be part of the input control inside the textfield, otherwise the user will never be able to type . or ,

Upvotes: 1

Related Questions