Can someone explain what is happening under the hood and how can i get the expected result? I am trying to convert some string and add them eg. '1.7888884448', '2.359848484' and '3.78333833' to 1.8 , 2.4 and 3.8 Then do 1.8+2.4+3.8 = 8 . how can i achieve cause :
let x = parseFloat('95.568').toFixed(2) + 2 // it's concatenating
console.log (x)
// output 95.572
console.log(typeof x)
// out put 'string'
let y =  parseFloat('95.568') + 2 
console.log (y)
// output 97.568
console.log(typeof y)
// out put 'number'
                You can first add them and then achieve accuracy to 2 decimal points. The result will be more accurate.
function addDecimalStrings(decimalStringArr) {
    let sum = 0;
    for(let i=0; i<decimalStringArr.length; i++){
        // Parse and add
        sum = sum + parseFloat(decimalStringArr[i]);
    }
    // Convert to two decimal points
    return sum.toFixed(2);
}
                        Simply put another parseFloat around, it will keep the decimal number :
parseFloat(parseFloat("9.55656").toFixed(2))
9.56
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With