本文共 1423 字,大约阅读时间需要 4 分钟。
javascript 逗号
I had a problem: I had a string that contained a decimal number, but the user could write it in two ways, using a dot, or a comma:
我有一个问题:我有一个包含十进制数字的字符串,但是用户可以用两种方式写它,使用点或逗号:
0,320.32
Different countries use different ways to separate the integral part from the decimal part of a number.
不同的国家/地区使用不同的方法将数字的整数部分与小数部分分开。
So I decided to convert the string to using a dot whenever I found a comma.
因此,我决定在发现逗号时将字符串转换为使用点。
I used a simple regular expression to do that:
我使用一个简单的正则表达式来做到这一点:
let value = '0,32'value = value.replace(/,/g, '.') //value is now '0.32'
You can do the opposite using replace(/\./g, ',')
(note the \
before the .
to escape it, since it’s a special character in )
你可以使用相反的replace(/\./g, ',')
注意\
之前.
逃避它,因为它是在一个特殊字符 )
The g
flag in the regex makes sure that if there are multiple instances of a comma (or dot, in the second example) they are all converted.
正则表达式中的g
标志可确保如果有多个逗号实例(在第二个示例中为点,则为点)都将被转换。
This is not something that applies to our use case, and I think we need to do more validation to check the integrity of our input here, but it’s a start.
这不适用于我们的用例,我认为我们需要做更多的验证来检查我们输入的完整性,但这只是一个开始。
In my case, after doing this substitution I called parseFloat(value) to get the float from the string, and then I limited the decimals number to 2 using toFixed(2):
就我而言,执行此替换后,我调用parseFloat(value)从字符串中获取浮点数,然后使用toFixed(2)将小数位数限制为2:
value = parseFloat(value).toFixed(2)
翻译自:
javascript 逗号
转载地址:http://komgb.baihongyu.com/