Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

ex:

"54.3" --> 54.3
like image 461
Kode_12 Avatar asked Nov 18 '16 19:11

Kode_12


People also ask

Which function converts the string value into number value?

In JavaScript parseInt() function (or a method) is used to convert the passed in string parameter or value to an integer value itself. This function returns an integer of base which is specified in second argument of parseInt() function.

Which function is used to convert a string or a number into a whole number?

In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.


2 Answers

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.

like image 105
Chris Haugen Avatar answered Oct 08 '22 20:10

Chris Haugen


You can use:

//pass String as argument
var floatVal = parseFloat("54.3");
console.log(floatVal);
like image 28
Pritam Banerjee Avatar answered Oct 08 '22 20:10

Pritam Banerjee