0

I want to format my numbers and I want these results.

I have tried .toFixed(2) but it didn’t yield the expected results.

Input     Result
50.000 => 50
50.900 => 50.9
50.940 => 50.94
50.941 => 50.94

Something like 0.## as formatting but in JavaScript.

Reza
  • 18,865
  • 13
  • 88
  • 163
  • I think you're looking for something like this parseFloat(Math.round(num3 * 100) / 100).toFixed(2); which is explained in this post -> http://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places – Robert Nov 24 '15 at 19:48
  • @robert No the reverse of that – Reza Nov 24 '15 at 19:48
  • 1
    Possible duplicate of [JavaScript: remove insignificant trailing zeros from a number?](http://stackoverflow.com/questions/3612744/javascript-remove-insignificant-trailing-zeros-from-a-number) – isherwood Nov 24 '15 at 19:49
  • 1
    `parseFloat(num.toFixed(2))` will do the trick – m90 Nov 24 '15 at 19:51
  • @m90 yes you are right ;) – Reza Nov 24 '15 at 19:56

3 Answers3

1

function decimalFunction() {
  console.log('click');
  var myvalue = document.getElementById('myInput').value;
  var decimal = Math.round(myvalue * 100) / 100
  document.getElementById('result').innerHTML  = decimal;
}
<input id="myInput" type="text"/>
<button onclick="decimalFunction()">Submit</button>
<div id="result"></div>
Math.round(inputNumber * 100) / 100

Input: 50.000, 50.900, 50.940, 50.941

Output: 50, 50.9, 50.94, 50.94

indubitablee
  • 8,136
  • 2
  • 25
  • 49
1

You should be able to use

parseFloat(num.toFixed(2));

to

  • have a maximum of two trailing digits
  • omit any superfluous trailing zeros
m90
  • 11,434
  • 13
  • 62
  • 112
  • your answer is also correct, sorry but I cannot flag two answer as right answer, only +1 :( – Reza Nov 24 '15 at 20:04
0

change you number to string. After some string operations you can get correct result

<script language="Javascript">
    var data = 50.947;
    var res = data.toString().substring(0, data.toString().indexOf('.') + 3);
    alert(res);
</script>
Ramin Darvishov
  • 1,043
  • 1
  • 15
  • 30