简体   繁体   中英

Round values with 2 decimal places and add 0 if not decimal are present

Round values with 2 decimal places and add 0 if not decimal are present

Hi, how I can round a value maintaining 2 decimal places? I try with Math.round(val) but doesn't work. Takes these numbers as examples:

25 should be converted to 25.00 25.3666 should be rounded to 25.37 25.55333 should be rounded to 25.55

Any help?

Have a look at toFixed() .

var a = 2;
a = a.toFixed(2);

now a is 2.00

Please note, that the returned value is a string, use with caution.

There are two ways of doing it:

first:

use Math.ceil for round up

for eg:

Math.ceil("your digits");

Also you can use the following

parseFloat("123.456").toFixed(2);

Math.round(num * 100) / 100

这应该工作。

Use .toFixed() function as below.

var num = 5.56789;
var n = num.toFixed(2);
// OUTPUT n = 6.57

The toFixed() method converts a number into a string, keeping a specified number of decimals.

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