0

I'm aware that the way to truncate a number to 2 decimal places in toFixed(). However, in case the number has just 1 decimal place, I get an error.

What is the way to mandate a number to display >2 decimal places(numbers after the decimals will be 0 in this case) so that toFixed() will not throw an error?

tereško
  • 58,060
  • 25
  • 98
  • 150
neuDev33
  • 1,573
  • 7
  • 41
  • 54
  • 3
    What is the error? I don't know any browser where `toFixed` should be throwing an error in that scenario. – David Hedlund Mar 12 '12 at 20:01
  • 3
    What error? http://jsfiddle.net/JamesHill/AbPEz/ – James Hill Mar 12 '12 at 20:02
  • Hm... normally, `toFixed` should add zeros at the end to match the required number of places. `var num = 10; var result = num.toFixed(2);` should product `10.00`. – Aleks G Mar 12 '12 at 20:02
  • Please post your code... toFixed works as intended for me (e.g.: `a=1.2; a.toFixed(4);` -> returns 1.2000) – nico Mar 12 '12 at 20:03
  • http://stackoverflow.com/questions/4895760/javascript-jquery-float-validating – zod Mar 12 '12 at 20:03
  • Kindof odd. `var num = 10; num.toFixed(2);` works, however `10.toFixed(2)` does not. *(testing with google chrome in console)* – Kevin B Mar 12 '12 at 20:06
  • I think the jQuery tag should be removed. The question doesn't involve it (`toFixed` is plain old Javascript), and I'm betting answers won't require it. http://jsfiddle.net/umJRt/ - note the "No-Library (pure JS)" on the left. – Merlyn Morgan-Graham Mar 12 '12 at 20:10
  • 1
    `10.toFixed(2)` don't work... but `(10).toFixed(2)` works :] – Rafael Verger Mar 12 '12 at 20:11
  • Voting to close because I cannot repro the error with the information provided. The question, as is, is incomplete. neuDev33, please provide a minimal code sample that repros the problem, and if it is browser specific let us know which browser you're using that is causing problems. – Merlyn Morgan-Graham Mar 12 '12 at 20:14

2 Answers2

1

This should work on any input:

var result = Math.round(original*100)/100;

Generally, I would avoid using toFixed(), as it can behave unexpectedly when given non float input. Also, see here:

How to format a float in javascript?

Trying to format number to 2 decimal places jQuery

Community
  • 1
  • 1
kmh
  • 391
  • 3
  • 13
1

I think you are trying to apply toFixed on a string ? You could just parse it into a float before using toFixed on it.

var a = '1.0'; 
a = parseFloat( a ); 
a = a.toFixed(2); 
console.log( a ); 
aziz punjani
  • 25,586
  • 9
  • 47
  • 56
  • I'm still not sure what the problem was, but I made a few code changes and toFixed works just fine now. – neuDev33 Mar 15 '12 at 16:38