admin管理员组

文章数量:1287511

How I can round a value maintaining 2 decimal places? I have tried using 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

How I can round a value maintaining 2 decimal places? I have tried using 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
Share Improve this question edited Dec 31, 2022 at 18:15 Skully 3,1263 gold badges27 silver badges41 bronze badges asked Apr 25, 2017 at 5:54 JagadeeshJagadeesh 1212 silver badges7 bronze badges 2
  • Use .toFixed(2); --- like parseFloat("123.456789").toFixed(2); – prog1011 Commented Apr 25, 2017 at 5:59
  • var m = parseFloat(fullamount).toFixed(2); Its working fine. Thanks – Jagadeesh Commented Apr 25, 2017 at 6:13
Add a ment  | 

4 Answers 4

Reset to default 5

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.

Math.round(num * 100) / 100

This should work.

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

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.

本文标签: javascriptRound values with 2 decimal places and add 0 if not decimal are presentStack Overflow