javascript - 仅当数字少于两位小数时才添加 .00 (toFixed)

标签 javascript number-formatting

我需要添加零,以便每个数字至少有两位小数,但不四舍五入。例如:

5      --> 5.00
5.1    --> 5.10
5.11   --> 5.11 (no change)
5.111  --> 5.111 (no change)
5.1111 -->  5.1111  (no change) 

我的函数缺少一个 IF 来检查少于两个小数位:
function addZeroes( num ) {
   var num = Number(num);
   if ( //idk ) {
      num = num.toFixed(2);
   }
   return num;
}

谢谢!

除了下面的两个之外,还发布了一个替代答案。 (请记住,我不是专家,这只是用于文本输入,而不是用于解析可能存在浮点问题的颜色等复杂值等)
function addZeroes( value ) {
    //set everything to at least two decimals; removs 3+ zero decimasl, keep non-zero decimals
    var new_value = value*1; //removes trailing zeros
    new_value = new_value+''; //casts it to string

    pos = new_value.indexOf('.');
    if (pos==-1) new_value = new_value + '.00';
    else {
        var integer = new_value.substring(0,pos);
        var decimals = new_value.substring(pos+1);
        while(decimals.length<2) decimals=decimals+'0';
        new_value = integer+'.'+decimals;
    }
    return new_value;
}

[这不是重复的问题。您链接的问题假定“知道它们至少有 1 个小数”。文本输入中不能假设小数点,这是错误的。]

最佳答案

干得好:

function addZeroes(num) {
// Convert input string to a number and store as a variable.
    var value = Number(num);      
// Split the input string into two arrays containing integers/decimals
    var res = num.split(".");     
// If there is no decimal point or only one decimal place found.
    if(res.length == 1 || res[1].length < 3) { 
// Set the number to two decimal places
        value = value.toFixed(2);
    }
// Return updated or original number.
return value;
}

// If you require the number as a string simply cast back as so
var num = String(value);
fiddle进行演示。

编辑:自从我第一次回答这个问题以来,javascript 和我都取得了进步,这是一个使用 ES6 的改进解决方案,但遵循相同的想法:
function addZeroes(num) {
  const dec = num.split('.')[1]
  const len = dec && dec.length > 2 ? dec.length : 2
  return Number(num).toFixed(len)
}
Updated fiddle

编辑2:或者如果您使用可选链接,您可以在一行中执行此操作,如下所示:
const addZeroes = num => Number(num).toFixed(Math.max(num.split('.')[1]?.length, 2) || 2)
Updateder fiddle

关于javascript - 仅当数字少于两位小数时才添加 .00 (toFixed),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24038971/

相关文章:

ios - 使用 numberFromString 生成 NSDecimalNumber 时如何获得没有分数错误的舍入值?

javascript - 如何在angularjs中对数字进行复数化和格式化

ios - 倒计时期间 iOS UILabel 中的小数点对齐?

python - 如何在 Python 中格式化具有可变位数的数字?

javascript - 将文本添加到第一个子路径的书签

javascript - HTML5 视频源作为本地存储的 blob 不再工作

javascript - 如果验证测试中条件无法正常工作

javascript - 从数据库字段中提取值到复选框值 PHP

javascript - 与 window.onload 混淆

java - Android 本地化查询