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
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/
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.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly