【问题标题】:Javascript round with a zero at the end (fixed number of decimals)Javascript 以零结尾(固定小数位数)
【发布时间】:2012-10-01 01:32:39
【问题描述】:

我正在使用 javascript round 对数字进行四舍五入。但是当值为$106.70 时,输出仅显示$106.7 并且缺少最后一个0。如何为以零结尾的数字添加零,或者有没有比使用 if else 更简单的方法来检查这个?

【问题讨论】:

    标签: javascript numbers rounding


    【解决方案1】:

    您可以使用.toFixed 方法:

    var n = 106.72; console.log(n.toFixed(2)); //=> '106.72'
    var n = 106.70; console.log(n.toFixed(2)); //=> '106.70'
    var n = 106.7; console.log(n.toFixed(2)); //=> '106.70'
    var n = 106; console.log(n.toFixed(2)); //=> '106.00'
    

    它会四舍五入:

    var n = 106.76; console.log(n.toFixed(1)); //=> '106.8'
    

    【讨论】:

    • 最后一个怎么给106.70? :)
    猜你喜欢
    • 1970-01-01
    • 2020-03-10
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多