简体   繁体   English

解析本地化的javascript数字字符串

[英]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. 在Javascript中,我想以用户理解的格式向用户显示数字,以便他们可以对其进行编辑。 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". 这是因为,如果他们在法国,他们可能更喜欢编辑数字“ 1.000.000,5”,而如果他们在澳大利亚,则他们可能更喜欢编辑数字“ 1000 0000.5”或“ 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. 现代Javascript提供了Intl.NumberFormat API,但它似乎只处理产生数字,而不解析它们。

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? 例如,函数如何区分美国和法国的9,521? 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 https://repl.it/Eu7I/2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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