将数字值转换为美元格式,以正确的可见格式显示

时间:2018-09-18 00:22:17

标签: javascript jquery coldfusion

在扣除一些值但没有得到像$8,657.00这样的类型后,尝试在javascript中做诸如dollarFormat之类的事情

由于这是个小任务,我不想为此使用任何库,但是我想在数字前使用Alert作为$符号,但是当它们增加并放在正确的位置时如何管理数量和小数需要的地方

2 个答案:

答案 0 :(得分:1)

使用toLocaleStringhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toLocaleString

const dollarFormat = (amount) => {
    return amount.toLocaleString('en-US', {
        style: 'currency',
        currency: 'USD',
        minimumFractionDigits: 2
    })
}
 
console.log(dollarFormat(8657))

答案 1 :(得分:0)

您尚未指定要在CF还是JS中实现此目标,因此以下示例假定使用JS。您可以根据需要将逻辑转换为CF。

以下功能是使用REGEX格式化数字的功能:

function dollarFormat( amount, fractionDigits ) {
    if( isNaN( amount ) || isNaN( fractionDigits ) ) {
        throw 'Invalid arguments';
    }
    
    var splitResults = amount.toFixed( fractionDigits ).split( '.' ),
        integer = splitResults[ 0 ],
        fraction = splitResults[ 1 ] || '';
    return '$' + integer.replace( /([0-9])(?=(?:[0-9]{3})+(?:\.|$))/g, '$1,' ) + ( fraction.length ? '.' + fraction : '' );
}

console.log( dollarFormat( 8657.00, 2 ) );
console.log( dollarFormat( 8657.00, 0 ) );
console.log( dollarFormat( 12234348657.00000, 4 ) );
console.log( dollarFormat( 8657.000000000, 4 ) );

相关问题