gpt4 book ai didi

javascript - 使用正则 exp 对货币进行四舍五入

转载 作者:行者123 更新时间:2023-11-29 23:18:53 28 4
gpt4 key购买 nike

我有多种货币输入,即 1,869.96 美元。我需要将我的货币四舍五入为不带任何小数位的整数 1,870。

我使用的正则表达式是

"$"+ a.toFixed(0).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); 

任何人都可以帮助我修改现有的值以将值四舍五入为不带小数位的整数。谢谢。

最佳答案

试试这个:

    function formatVal(a){ 
var c = '';
if(a.toString().indexOf('$') !== -1){
a = Math.round(Number(a.toString().replace(/[^0-9\.-]+/g,"")));
if (isNaN(a)){
c=a;
}else {
c ="$"+a.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, '$&,');
if(c == '$0'){ c = "";}
}
}
return c;
}

console.log(formatVal('$1,869.96'));
console.log(formatVal('$1,869'));
console.log(formatVal('sssss'));
console.log(formatVal(42));

关于javascript - 使用正则 exp 对货币进行四舍五入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51527934/

28 4 0