简体   繁体   中英

parsing localized javascript number strings

In Javascript, I want to present a number to a user in a format they understand so that they can edit it. Consequently, the system will need to parse an international number.

This is because if they are in France they are likely to prefer to edit the number "1.000.000,5" whereas if they are in Australia, they are likely to prefer to edit the number "1 000 000.5" or "1,000,000.5". (To clarify the scope of the question: my code shouldn't have to know about the individual rules of this or that locale. Does any country use ! as a decimal point? I don't know, and I don't want to know.)

Modern Javascript provides the Intl.NumberFormat API, but it only seems to deal with producing numbers, not parsing them.

How can I parse a localized number?

I don't think it's possible without having pre-set the format and knowing what you are converting to/from.

For example, how can a function differentiate between 9,521 in the US and in France? In the US, that's over nine thousand, in France it's nine and a half (and a bit).

I'd recommend you keep a list of regex's for the different formats you will be displaying (and allowing in input) and use the appropriate one to parse the number when you read it in.

The rules are going to be have to be somewhere, and a reasonable place is in your program or you can use an external library if it exists. To generally answer your question. A number is broken up into groups of three to represents thousands, although in some countries they break up into other groups; eg Japan they break up number into groups. Here is a script to break a number up into groups of threes with a given spacing system.

https://repl.it/Eu7I/2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM