简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM