Javascript difference of 1 decimal [duplicate]

0

I have the following function, which takes the total of the invoice, adds the amounts that have been paid, subtracts them and obtains the total that remains to be paid:

function PagarTotal(){
    var total_a_pagar = $('#total_a_pagar').val();
    var pagado = 0;     
    for(i in pagos_adicionados){            
        pagado += Number(pagos_adicionados[i]['monto_pago']);
    }       
    total_a_pagar = Number(total_a_pagar) - Number(pagado);
    $('#monto_pago').val(total_a_pagar);
}

The problem is the following, in a simple transaction, with a bill of $ 5.35, payment $ 2 and the total to pay me back 3.3499999999999996, I do not understand where many decimals come from, by logic subtracting this should give a total from: $ 5.35 - $ 2 = $ 3.35

I've tried parseFloat and Number and the same thing happens with both functions.

Note: I can not use toFixed because this would round out the amounts and is not what I need, toFixed is practically a PATCH to fix this error timelessly.

    
asked by StevePHP 04.04.2018 в 15:52
source

3 answers

1

TOFIXED FUNCTION ()

You can use to launch the final value with only one or two decimals; the ones you just need:

The previous function helps me to delimit in parentheses the number of decimal numbers that will be shown after the point; As an example I leave this code

let valor = 12.43564353454
let valorNuevo = valor.toFixed(1)
console.log(valorNuevo)
  

As you can notice in the example, I have a long amount for that   say it with decimals, but before sending it to print I do   access the toFixed () function / method that enters its parentheses   I indicate the number of decimals I want to show and just after   then if I send to print the new variable

    
answered by 04.04.2018 в 15:57
1

It's a common mistake not only in JavaScript. I invite you to read

  

Because my programs can not do arithmetic calculations   correctly

an alternative solution is to use to.Fixed () , so you remove those Numbers that are unnecessary

const pagos_adicionados =  [300.2,12,19]
let total_a_pagar = 300
let pagado = 0;     
    for(i in pagos_adicionados){            
        pagado += (pagos_adicionados[i]);
    }       
    total_a_pagar = total_a_pagar - pagado;
    console.log(total_a_pagar.toFixed(2))
    
answered by 04.04.2018 в 16:00
1

You can try using toPrecision () , which allows you to choose the decimals you want, example:

let a = 5.35;
let b = 2 ;
let c= a -b ; 
console.log(c.toPrecision(3));
    
answered by 04.04.2018 в 16:03