neuDev33
neuDev33

Reputation: 1623

how to mandate a number to display 2 decimal places?

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?

Upvotes: 0

Views: 389

Answers (2)

aziz punjani
aziz punjani

Reputation: 25776

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 ); 

Upvotes: 1

kmh
kmh

Reputation: 421

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

Upvotes: 1

Related Questions