js 保留两位小数,去掉%

使用 JS 中的 isNaN() 函数来判断是否数值,同时还需要判断是否为 null 或者为空字符串,如果都不是,则使用 toFixed() 函数保留两位小数,否则不进行处理。

function formatNumber(num) {
  if (num !== null && num !== "" && !isNaN(num)) {
    return parseFloat(num).toFixed(2);
    // return Math.round(num * 100) / 100
  } else {
    if(num && num.includes('%')) {
      return parseFloat(num.replace("%", "")).toFixed(2)
    }
    return num;
  }
}

// 测试
console.log('3.1415926的结果---', formatNumber(3.1415926)); // 输出 3.14
console.log('"23.456"的结果----', formatNumber("23.456")); // 输出23.46
console.log('0的结果---', formatNumber(0)); // 输出 0.00
console.log('undefined的结果---', formatNumber(undefined)); // 输出 undefined
console.log('空的结果---', formatNumber("")); // 输出 ""
console.log('null的结果---', formatNumber(null)); // 输出 null
console.log('"null"的结果---', formatNumber("null")); // 输出 null
console.log('hello的结果---', formatNumber("hello")); // 输出 hello
console.log("12.567%的结果---", formatNumber("12.567%")); // 输出 12.57
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值