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

round off currency using regular exp

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

我使用的正则表达式是

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

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

试试这个:

    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 == '[=10=]'){ c = "";}
        } 
    }
    return c; 
}
    
console.log(formatVal(',869.96'));
console.log(formatVal(',869'));
console.log(formatVal('sssss'));
console.log(formatVal(42));