【问题标题】:Remove decimal values删除十进制值
【发布时间】:2018-01-18 14:05:21
【问题描述】:

只有当所有十进制值都是0时,我才想删除十进制值。

如果我使用parseFloat():

50.00 => 50
60.50 => 60.5

我的预期输出:

50.00 => 50
60.50 => 60.50

我不能使用Math.round()Math.trunk()Math.floor()ParseInt()

还有其他方法吗?

【问题讨论】:

  • 你有一个字符串并且想要一个字符串回来吗?
  • JavaScript 不支持尾随零。所以如果你想要它们,你必须使用字符串。
  • 它很难看/很棘手,但它也可以工作:你不能只使用数字作为字符串并调用parseFloat(),如果它匹配像\.0*这样的正则表达式

标签: javascript numbers decimal


【解决方案1】:

你可以试试这个:

const formatTo = n => Number.isInteger(n) ? n : parseFloat(n).toFixed(2);

console.log(formatTo(50.00))
console.log(formatTo(60.50))

【讨论】:

  • 迄今为止最优雅的答案。
【解决方案2】:

使用toFixed() 和正则表达式/[.,]00$/replace(),如下所示:

var num1 = (50.00).toFixed(2).replace(/[.,]00$/, "");
var num2 = (60.50).toFixed(2).replace(/[.,]00$/, "");
console.log(num1)
console.log(num2)

【讨论】:

    【解决方案3】:

    使用给定的字符串,您可以删除小数点后的所有零。

    var values = ['50.00', '60.50'];
    
    console.log(values.map(s => s.replace(/\.0*$/, '')));

    【讨论】:

      【解决方案4】:

      由于 JavaScript 不支持尾随零,我假设您正在处理数字并且必须将它们转换为字符串。因此,在这种情况下,您需要使用 toFixed() 并删除双零

      function trimZeros (num) {
        return num.toFixed(2).replace(/\.00/,"")
      }
      
      console.log(50, trimZeros(50))
      console.log(60.5, trimZeros(60.5))
      console.log(0.5, trimZeros(0.5))
      console.log(100.01, trimZeros(100.01))

      如果它只是你拥有的一个字符串,那么你可以在它上面做一个 reg exp

      function trimZeros (numStr) {
        return numStr.replace(/\.00/,"")
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-02-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-04
        • 2011-01-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多