博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
javascript 逗号_如何使用JavaScript将逗号更改为点
阅读量:2507 次
发布时间:2019-05-11

本文共 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/

你可能感兴趣的文章
大数据学习之路------借助HDP SANDBOX开始学习
查看>>
Hadoop基础学习:基于Hortonworks HDP
查看>>
为什么linux安装程序 都要放到/usr/local目录下
查看>>
Hive安装前扫盲之Derby和Metastore
查看>>
永久修改PATH环境变量的几种办法
查看>>
大数据学习之HDP SANDBOX开始学习
查看>>
Hive Beeline使用
查看>>
Centos6安装图形界面(hdp不需要,hdp直接从github上下载数据即可)
查看>>
CentOS7 中把yum源更换成163源
查看>>
关于yum Error: Cannot retrieve repository metadata (repomd.xml) for repository:xxxxxx.
查看>>
2020-11-18
查看>>
Docker面试题(二)
查看>>
【NOI 2018】归程(Kruskal重构树)
查看>>
注册用户
查看>>
TZC Intercommunication System
查看>>
HDU 4571 SPFA+DP
查看>>
centos 创建以日期为名的文件夹
查看>>
Java Timer触发定时器
查看>>
Page Object设计模式
查看>>
程序的基础知识
查看>>