How can I prevent a string value from getting rounded when converted to a number value?

You can use:

//pass String as argument
var floatVal = parseFloat("54.3");
console.log(floatVal);


An integer is a whole number.

A Float is a number with decimal values.

Knowing this you will want to use parseFloat(), which will take the period into consideration; instead of parseInt() which will round to the nearest whole number.

Refer to: these docs for more detailed information

So the answer is:

parseFloat("string");

you can also do this which is known as a unary plus:

let a = "54.3"

a = +a;

Doing +a is practically the same as doing a * 1; it converts the value in a to a number if needed, but after that it doesn't change the value.


You can even use Number as a function to numeric strings to a number:

Number("54.3") // 54.3

Note the following:

  • parseFloat is supposed to parse a numeric value from a string and succeeds if beginning of string, if not all, is numeric.

  • Number constructor or function checks if the entire string is numeric.

  • +"54.3" is exactly the same as Number("54.3") behind the scene.