Kode_12 Kode_12 - 1 year ago 62
Javascript Question

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

I have an input field that accepts numeric values. I'd like to find a method that converts that that string value into a number value.

ParseInt() was what first came to find, then toFixed().

What do these have in common? It rounds the values to its Integer value (like ParseInt suggests--I know!).

How can I convert a string representation into a number value while retaining any decimal values?


"54.3" --> 54.3

I apologize if this is a duplicate question.

Answer Source

An integer is a whole number.

A Float is a number with decimal values.

Knowing this you will want to use parseFloat(), not 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:


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download