float时显示小数点后2位,int时显示小数点后0位
Display decimal 2 places if float, and display decimal 0 places if int
我知道如何计算小数点后 2 位。
使用 toFixed(2);
但问题是列表中的所有数字始终是小数点后两位。
我想如果分数使用小数 2 位,如果非分数使用小数 0 位。
number display
------ -------
1 1
3 3
1.341 1.34
1.345555 1.35
2 2
试试这个
function isInt(n) {
return n % 1 === 0;
}
var num=3.00;
if (isInt(num)){alert(num);}
else{alert(num.toFixed(2));}
function show(num) { // test for int is from duplicate question
return (num % 1 === 0)?num:num.toFixed(2);
}
var nums = [1,3,1.341,1.345555,2],div=document.getElementById("res");
for (var i=0;i<nums.length;i++) {
res.innerHTML+='<br/>'+show(nums[i]);
}
<div id="res"></div>
我知道如何计算小数点后 2 位。
使用 toFixed(2);
但问题是列表中的所有数字始终是小数点后两位。
我想如果分数使用小数 2 位,如果非分数使用小数 0 位。
number display
------ -------
1 1
3 3
1.341 1.34
1.345555 1.35
2 2
试试这个
function isInt(n) {
return n % 1 === 0;
}
var num=3.00;
if (isInt(num)){alert(num);}
else{alert(num.toFixed(2));}
function show(num) { // test for int is from duplicate question
return (num % 1 === 0)?num:num.toFixed(2);
}
var nums = [1,3,1.341,1.345555,2],div=document.getElementById("res");
for (var i=0;i<nums.length;i++) {
res.innerHTML+='<br/>'+show(nums[i]);
}
<div id="res"></div>