Javascript 用两位小数格式化数字变量
我有以下带有两个变量的javascript代码:Javascript 用两位小数格式化数字变量,javascript,Javascript,我有以下带有两个变量的javascript代码: eventTotal = eventTotal + parseFloat(currentElement.title).toFixed(2); deliveryTotal = deliveryTotal + parseFloat(currentElement.title).toFixed(2); 每当我使用以下方法将变量添加到一起时: totalbox.value = "£" + eventTotal + deliveryTotal; 产出一
eventTotal = eventTotal + parseFloat(currentElement.title).toFixed(2);
deliveryTotal = deliveryTotal + parseFloat(currentElement.title).toFixed(2);
每当我使用以下方法将变量添加到一起时:
totalbox.value = "£" + eventTotal + deliveryTotal;
产出一般为“055.0003.99英镑”
为什么此数字格式不正确?我如何实现此目的?
toFixed
返回字符串,而不是数字。因此,为了进行加法而不是串联(使用+
),您必须将值转换回数字:
totalbox.value = "£" + (parseFloat(eventTotal) + parseFloat(deliveryTotal)).toFixed(2);
FWIW:相反,您可以使用前缀+
作为parseFloat
的一种快捷方式:
totalbox.value = "£" + (+eventTotal + +deliveryTotal).toFixed(2);
toFixed
返回字符串,而不是数字。因此,为了进行加法而不是串联(使用+
),您必须将值转换回数字:
totalbox.value = "£" + (parseFloat(eventTotal) + parseFloat(deliveryTotal)).toFixed(2);
FWIW:相反,您可以使用前缀+
作为parseFloat
的一种快捷方式:
totalbox.value = "£" + (+eventTotal + +deliveryTotal).toFixed(2);
得到总数并使用
toFixed(2)
得到总数并使用
toFixed(2)
每个人都指出了这个问题,它是由
.toFixed()
返回字符串引起的,但是所有重复调用parseFloat()
、toFixed()
和casting都是一个问题
最好将所有变量都保留为数字,并通过一个函数将它们转换为人类可读的货币
// convert to currency
function currencyFormat(amount){
return '£' + (amount*1).toFixed(2);
}
// cast to a number in one place
eventTotal = eventTotal*1;
deliveryTotal = deliveryTotal*1;
// now work with the variables however you need, knowing that you always have numbers
// output currency
totalbox.value = currencyFormat(eventTotal + deliveryTotal);
eventbox.value = currencyFormat(eventTotal);
现在,如果您需要更改货币符号,或者想要更改小数点分隔符或小数位数,那么这只是可重用代码中的一个更改。此外,还应使用HTML实体
£
而不是使用原始符号。每个人都指出了这个问题,它是由.toFixed()
返回字符串引起的,但是所有对parseFloat()
、toFixed()
和强制转换的重复调用都是错误的
最好将所有变量都保留为数字,并通过一个函数将它们转换为人类可读的货币
// convert to currency
function currencyFormat(amount){
return '£' + (amount*1).toFixed(2);
}
// cast to a number in one place
eventTotal = eventTotal*1;
deliveryTotal = deliveryTotal*1;
// now work with the variables however you need, knowing that you always have numbers
// output currency
totalbox.value = currencyFormat(eventTotal + deliveryTotal);
eventbox.value = currencyFormat(eventTotal);
现在,如果您需要更改货币符号,或者想要更改小数点分隔符或小数位数,那么这只是可重用代码中的一个更改。此外,还应使用HTML实体
£
而不是使用原始符号。toFixed
返回一个字符串,因此您只需连接字符串。获取总数,然后对结果调用toFixed
。获取总数,然后对结果调用toFixed
。记住