【问题标题】:I want my value modified to ALWAYS have three decimal digits我希望我的值修改为始终具有三位小数
【发布时间】:2022-11-19 16:24:34
【问题描述】:

我的逻辑根据用户输入计算并返回一个值,我想将该值修改为始终具有三位小数

例如;

11.000
1.021.020
2.0000042.000
2.56872.569

我将如何在 javascript 上实现它?

【问题讨论】:

    标签: javascript decimal rounding decimal-point


    【解决方案1】:

    你可以使用Number().toFixed()来做

    const formatVal = (val,precise = 3) =>{
      return Number(val).toFixed(precise)
    }
    
    console.log(formatVal(1,3))
    console.log(formatVal(1.02,3))
    console.log(formatVal(2.000004,3))
    console.log(formatVal(2.5687))
    console.log("-----------------")
    console.log(formatVal(2.5687,2))

    【讨论】:

      【解决方案2】:

      你可以做这样的事情,

      let newNum  = Number(1.34).toFixed(3);
      console.log(newNum);

      【讨论】:

        猜你喜欢
        • 2020-07-02
        • 2020-10-27
        • 1970-01-01
        • 2011-10-11
        • 2012-08-05
        • 2011-08-06
        • 1970-01-01
        • 1970-01-01
        • 2016-08-17
        相关资源
        最近更新 更多