Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

parsing numbers in a specific Locale

Status
Not open for further replies.

Hokkie

MIS
Nov 21, 2001
77
NL
Hi,

I need to parse a float from a textbox that may be formatted like "150000" or like "150.000,00"--Dutch Locale.

If I use parseFloat on "150.000,00" what I get is 150. What I need is 150000. Using Locale in parsing would be good, but parseFloat doesn't take Locale as a parameter.

Does anybody know how to parse "150.000,00" into 150000 using Javascript?

Thanks in advance.

 
You could replace all "," with ".", and all "." with ",", and parse the result.

If you need to allow both formats without messing it up, take the text the user entered, and run it through Number.toLocaleString. If the result is the same as the data you entered, then you know that the user entered a localised number, and so you need to convert it.

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Thanks, Dan.

I've chosen to get rid of the thousand-separator and replace the decimal point/comma with a point, using the replace function. So that "150.000,00" becomes "150000.00".

parseFloat handles this correctly and it solves my problem, albeit not very satisfactory or elegantly.

I'm still open to other suggestions, but the urgency is now gone.

 
[1] You can do it like this. Suppose the string variable,s say, be retrieved from so form field value. In the validation routine, you establish this.
[tt]
var dsep=(1/2).toString().charAt(1);
var tsep=(dsep==".")?",":".";

var rx=new RegExp("^(\\d{1,3}(\\"+tsep+"\\d{3})*(\\"+dsep+"\\d+)?|(\\d+))(\\"+dsep+"\\d+)?$");

//var s=document.someform.somefield.value;
//validation would be done like this with bval true for valid and false for invalid
var bval;

//the replace part is to trim insignificant leading/trailing spaces
bval=rx.test(s.replace(/(^\s*|\s*$/,""));
[/tt]
[2] It will impose some restrictions on user inputs, either consistently using decimal and thousand separators or consistently plain without thousand separator.
[tt]
//suppose decimal separator eventually be the comma
//valid: 1234567; 123.456; 123.456.789,012; etc
//invalid: 12.34567; 123.456,; etc
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top