Abadi
Abadi

Reputation: 71

How to get the number from an input in JavaScript?

I have defined an input in HTML that represents a number. I need to parse the string in JavaScript to a number taking into consideration the different languages that will be entered by the user, for example: '1.34' in English will be written as '1,34' in French. parseFloat('1,344') will be return 1 in case we are in English standard.

Upvotes: 0

Views: 88

Answers (2)

TeachMeToAim
TeachMeToAim

Reputation: 33

If it's only those two representations you consider, then another easy solution is to always do

var floatNum = num.replace(/,/g,".");

and then just treat it like any float number.

Unless you really need it for other number systems I'd avoid using a library. Libraries tend to be too big for most projects to utilize properly in my opinion.

Upvotes: 0

dj-neza
dj-neza

Reputation: 308

You could probably find a library for it, but you can also pretty easily format the numbers into the wanted format yourself.

When you get a number from the input just convert it to string and then use the indexOf() function (http://www.w3schools.com/jsref/jsref_indexof.asp) to see if there's a comma or a dot in the number. It returns the position index of that element in a string so you can then replace with the wanted one to format the number. Position will be -1 if there is no dot/comma.

var num = 32.14;
var string = String(num);
var position = string.indexOf("."); 

Hope this helps you.

Upvotes: 1

Related Questions