Format any number to two place of decimal using JavaScript?


I am getting data from the server using jQuery data table, now I want to format all the price or numbers getting from the server to two decimal places using javascript.

How can I do it?

For example:

1 -> 1.00
120.1-> 120.10
116.123-> 116.12

Asked by:- bhanu
0
: 3076 At:- 4/20/2020 12:51:32 PM
Javascript math round number to two place decimals







2 Answers
profileImage Answered by:- vikas_jk

You format to 2 decimal using Number and .ToFixed()

Number(1).toFixed(2);         // 1.00
Number(120.641).toFixed(2);     // 120.64
Number(116.123).toFixed(2);     // 116.12

OR

You can use Math.Round with toFixed()

(Math.round(num * 100) / 100).toFixed(2);

Where num = number which you want to convert to 2 place of decimal.

You can try this fiddle

https://jsfiddle.net/Lzyxorkm/

 

1
At:- 4/20/2020 2:40:31 PM


profileImage Answered by:- pika

Nowadays, you can also use toLocaleString to format number upto 2 decimal place.

Here is the example for it

var numb = 2.435;
numb.toLocaleString("en-US", { maximumFractionDigits: 2, minimumFractionDigits: 2 });

Above code will return output as "2.44"

OR

Simply use .toPrecision which will not round numbers like above, but will only format for the specific number of decimal values, example:

var numb = new Number(12.12);
console.log(numb.toPrecision(2));//outputs 12
console.log(numb.toPrecision(3));//outputs 12.1
console.log(numb.toPrecision(4));//outputs 12.12

Hope it helps.

1
At:- 7/29/2021 7:03:59 AM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use