Error converting string to numeric value

Asked

Viewed 114 times

6

I have a string and I need to convert it to number, in case I need to convert it to a real value, but I’m not getting it. Below is an example where I try to convert the contents of a string into number so they can check.

const valor = parseFloat("109,99").toFixed(2)
console.log(valor, typeof valor)

In addition to not converting the value into a number, the code also returns me the wrong value because it was to return 109.99 instead of 109.00.

2 answers

6

What happens is that parseFloat accepts a string in a valid numeric Javascript format. In your case, the string is invalid, since the decimal box separator is a comma. This will cause all characters after it to be ignored. In Javascript, this tab must be a dot.

So before you do the parse of the string, you must ensure that the comma is replaced by a point:

const valor = parseFloat("109,99".replace(',', '.'));
console.log(valor, typeof valor); // 109.99 "number"

4

The problem is that to turn a value into a float, decimal separator should always be a point instead of a comma.

When you try to convert your string without treating it properly, the result is this:

console.log(parseFloat("109,99")); // Output: 109

In the code you used, the result came with zeros after the point because you were using the method toFixed, displaying numbers after the decimal point of a value.

console.log(parseFloat("5.4372").toFixed(2)) // Output: 5.44

What you can do then to solve the problem, is replace the comma to a point with the method replace before conversion.

See this example below:

var valor = "109,99";
var novo_valor = parseFloat(valor.replace(",", "."));

console.log(novo_valor, "|", typeof novo_valor); // Output: 109.99 | number

  • Don’t forget to declare the variables. ;)

  • 1

    Python Mania kkk But put var or not in the global scope makes no difference right ?

  • 2

    I have now seen the edition in the commentary. : ) In thesis, var today is falling into disuse. let and const are preferable. See more about this here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.