Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert floating point decimal separator from dot to comma in Javascript

Tags:

javascript

I have already tried the following:

discval = 2.833423
discval = discval.toFixed(2).toString().replace("." , ",");
discval = parseFloat(discval);

The output is 2 and not 2,83

Any idea?

like image 359
chrysst Avatar asked Feb 05 '16 11:02

chrysst


People also ask

How you convert a string to a floating point number in JavaScript?

Using the parseFloat() method The parseFloat() is a function in JavaScript, this accept the string as input and convert the value into a floating point number. Note − The parseFloat() will return the output as floating point number.

What is floating point precision in JavaScript?

It is a double precision format where 64 bits are allocated for every floating point. The displaying of these floating values could be handled using 2 methods: Using toFixed() Method: The number of decimal places in float values can be set using the toFixed() method.

What is the correct decimal separator?

Great Britain and the United States are two of the few places in the world that use a period to indicate the decimal place. Many other countries use a comma instead. The decimal separator is also called the radix character.


1 Answers

parseFloat("2,83") will return 2 because , is not recognized as decimal separator, while . is.

If you want to round the number to 2 decimal places just use parseFloat(discval.toFixed(2)) or Math.round(discval * 100) / 100;

If you need this jut for display purposes, then leave it as a string with a comma. You can also use Number.toLocaleString() to format numbers for display purposes. But you won't be able to use it in further calculations.

BTW .toFixed() returns a string, so no need to use .toString() after that.

like image 134
pawel Avatar answered Nov 02 '22 02:11

pawel