How to return correctly the values of calculations with decimals in javascript?

Asked

Viewed 560 times

5

I have following code someone could help as it would be solution for this.


var resultado  =(parseFloat(126,79) +  parseFloat(237,00)).toFixed(2); 

javascript result = 363,00

correct value = 363,79

4 answers

6

I think that’s what you want:

 

var resultado  = parseFloat("126,79".replace(',', '.')) + parseFloat("237,00".replace(',', '.'));
console.log(resultado);

//valor correto = 363,79

The reason for this is that parseFloat() when you find the comma deletes what comes next and since these values start as strings you can simply make a replace of the comma per point

If the result is going to be a value with 3 decimal places you can round as follows:

var resultado  = parseFloat("126,79".replace(',', '.')) +  parseFloat("237,201".replace(',', '.'));
console.log('Sem arredondar: ' +resultado);
resultado = Math.round(resultado * 100) / 100; // arredondar para 2 casas decimais
console.log('Arredondado: ' +resultado);

//valor correto = 363.991

  • 2

    perfect thanks solved.

  • 1

    You’re welcome @Eduardosampaio, I’m glad you decided

2

Use "." instead of ","

 var resultado  =(parseFloat(126.79) +  parseFloat(237.00))

1

The decimal separator is . and not ,. The way you did, the numbers are being considered integer and not decimal.

var valor1 = parseFloat(126.79);
var valor2 = parseFloat(237.00);
var resultado  = valor1 + valor2;
console.log(resultado);

1

The use of the comma is wrong, when using number, no comma is used, the comma is represented by the dot in Javascript. the use of the parseFloat(), is parsing what he considers number, ie the value that comes after the comma is discarded:

var v1 = '126,79'; //recebe valor 1 em string
var v2 = '237,00'; //recebe valor 2 em string
v1 = v1.replace(/\,/gi,'.'); //troca a vírgula por ponto do valor 1
v2 = v2.replace(/\,/gi,'.'); //troca a vírgula por ponto do valor 2
var resultado = (parseFloat(v1) + parseFloat(v2)).toFixed(2); 

console.log(resultado);

Browser other questions tagged

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