How to correctly return the calculation values with decimals in javascript?

5

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

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

javascript result = 363.00

Correct value = 363.79

    
asked by anonymous 16.11.2016 / 19:30

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 it finds the comma deletes the following, and since these values begin with being strings it can simply do a replace of the comma by dot

If the result is a value with 3 decimal places, you can round it 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
    
16.11.2016 / 19:34
2

Use "." instead of ","

 var resultado  =(parseFloat(126.79) +  parseFloat(237.00))
    
16.11.2016 / 19:35
1

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

var valor1 = parseFloat(126.79);
var valor2 = parseFloat(237.00);
var resultado  = valor1 + valor2;
console.log(resultado);
    
16.11.2016 / 19:35
1

The use of the comma is wrong, when using number, no comma is used, the comma is represented by the JavaScript point. the use of parseFloat() , is parse of what it considers number, that is, 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);
    
16.11.2016 / 20:36