【问题标题】:Formatting number var with two decimal places [duplicate]格式化带两位小数的数字var [重复]
【发布时间】:2014-04-22 16:02:31
【问题描述】:

我有以下带有两个变量的 javascript 代码:

eventTotal = eventTotal + parseFloat(currentElement.title).toFixed(2);

deliveryTotal = deliveryTotal + parseFloat(currentElement.title).toFixed(2);

每当我将变量添加在一起时:

totalbox.value = "£" + eventTotal + deliveryTotal;

输出通常类似于“£055.0003.99”。

为什么这个数字格式不正确,我该如何实现?

【问题讨论】:

  • toFixed 返回一个字符串,所以你只是连接字符串。获取总数,然后在结果上调用toFixed

标签: javascript


【解决方案1】:

toFixed 返回一个字符串,而不是一个数字。因此,为了进行加法而不是连接(使用+),您必须将值转换回数字:

totalbox.value = "£" + (parseFloat(eventTotal) + parseFloat(deliveryTotal)).toFixed(2);

FWIW:你可以使用前缀+作为parseFloat的快捷方式:

totalbox.value = "£" + (+eventTotal + +deliveryTotal).toFixed(2);

【讨论】:

    【解决方案2】:

    每个人都指出了这个问题,由.toFixed() 返回一个字符串引起,但是所有这些对parseFloat()toFixed() 和强制转换的重复调用都是code smell

    最好将所有变量保留为数字,然后通过函数将它们传递给人类可读的货币。

    // 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 实体 £ 而不是使用原始符号。

    【讨论】:

      【解决方案3】:

      获取总数并使用

      toFixed(2);

      eventTotal = (eventTotal + parseFloat(currentElement.title)).toFixed(2);
      
      deliveryTotal = (deliveryTotal + parseFloat(currentElement.title)).toFixed(2);
      

      【讨论】:

        猜你喜欢
        • 2021-09-03
        • 2011-06-04
        • 2014-08-18
        • 1970-01-01
        • 2016-09-28
        • 1970-01-01
        • 2015-02-12
        • 2011-03-22
        • 1970-01-01
        相关资源
        最近更新 更多