Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format numbers in javascript to two decimal digits?

Tags:

javascript

I need to format numbers to two decimal digits in javascript. In order to do this I am using toFixed method which is working properly.

But in cases, where numbers don't have any decimal digits, it should not show decimal point

e.g. 10.00 should be 10 only and not 10.00.

like image 336
ashishjmeshram Avatar asked Dec 11 '22 01:12

ashishjmeshram


1 Answers

.toFixed() converts your result to String,
so you need to make it back a Number: jsBin demo

parseFloat( num.toFixed(2) )

or by simply using the Unary +

+num.toFixed(2)

both will give the following:

//   15.00   --->   15
//   15.20   --->   15.2

If you only want to get rid of the .00 case, than you can go for String manipulation using .replace()

num.toFixed(2).replace('.00', '');

Note: the above will convert your Number to String.

like image 133
Roko C. Buljan Avatar answered Jan 16 '23 20:01

Roko C. Buljan