0

I know how to do decimal 2 places.

use toFixed(2); but the problem is all of number in list is always 2 decimal places.

I want to if fraction use decimal 2 places, if non fraction use decimal 0 places.

number     display
------     -------
1          1
3          3
1.341      1.34
1.345555   1.35
2          2
mplungjan
  • 169,008
  • 28
  • 173
  • 236
riseres
  • 3,004
  • 4
  • 28
  • 40

2 Answers2

2

Try this

function isInt(n) {
       return n % 1 === 0;

    }
    var num=3.00;
    if (isInt(num)){alert(num);}
    else{alert(num.toFixed(2));}
EugenSunic
  • 13,162
  • 13
  • 64
  • 86
1

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236