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.
Asked
Active
Viewed 1,054 times
4 Answers
2

Community
- 1
- 1

Vinay Pratap Singh Bhadauria
- 9,829
- 3
- 28
- 49
-
thanks , but wen iam using toFixed() method then number is rounding and iam getting the values dynamically(what is user entered). – SimSam Mar 21 '14 at 10:52
-
@SimSam give me some no's example, i am sure we can find an alternative – Vinay Pratap Singh Bhadauria Mar 21 '14 at 10:54
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.
- 64,864
- 9
- 122
- 138