我需要添加零,以便每个数字至少有两位小数,但不四舍五入。例如:
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/