仅在小数点逗号前添加千位分隔符 [英] Only add thousand separator before decimal comma
问题描述
我在stackoverflow上找到了一个正则表达式来添加,"或.".根据您的语言,每三分之二后的数字.
I have found a regex on stackoverflow to add a ',' or '.' after every third number depending on your language.
(\d)(?=(\d\d\d)+(?!\d))
问题在于,当我们到达小数点时也会发生这种情况,例如:
The problem is that it also happens when we reach the decimal point like with for example:
5487445.46878
使用以下代码(和正则表达式)的结果是:
The result of that with the following code (and regex) is:
return number.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
这将导致:
5,487,445.46,878
当我根据您的语言来转换数字时,我正在使用此正则表达式.例如,在荷兰语中,逗号用作分隔符,因此我要执行以下操作:
I'm using this regex when I'm converting a number depending on your language. In Dutch for example a comma is used as a seperator, so there I do the following:
return number.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1.")
这将导致
5.487.445,46.878
这些当然需要成为:
5,487,445.46878
和
5.487.445,4687
有人知道我需要在哪里更新正则表达式以忽略小数点吗?
推荐答案
您可以使用RegEx
,但如果其中包含逗号或点,请先将其拆分.
You can use your RegEx
but split your number first if its has a comma or point in it.
var input = '5487445.46878';
var parts = input.split('.');
var part1 = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
var part2 = parts[1];
alert(part1 + '.' + part2);
这篇关于仅在小数点逗号前添加千位分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!