-4

Can anyone give me the code for accepting only 2 decimals using JavaScript. Without regular expression and without jQuery. The number should not be round.

SimSam
  • 3
  • 3

4 Answers4

2

To Fixed

use toFixed(2); for doing that

var num = 2.4;
alert(num.toFixed(2));  will alert 2.40
Community
  • 1
  • 1
Vinay Pratap Singh
  • 9,193
  • 3
  • 23
  • 49
0

Try with

parseFloat(Math.round(yourNum * 100) / 100).toFixed(2);
Wundwin Born
  • 3,279
  • 17
  • 35
0

try this one

 Math.round(num * 100) / 100
chriz
  • 1,311
  • 2
  • 16
  • 31
0

The number should not be round.

Use Math.floor to round down and you can use Math.pow to generically set the number of digits.

function trimDP(x, i) {
    var e = Math.pow(10, i || 0);
    return Math.floor(e * x) / e;
}
trimDP(2.45991, 2); // 2.45

If you want this as a String, you need to use .toFixed(i) after so that it doesn't get rounded.

var x = trimDP(2.40001, 2); // 2.4
x.toString(2); // "2.40"
Paul S.
  • 58,277
  • 8
  • 106
  • 120