Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parseFloat(x).toFixe(2) returns a string

Tags:

node.js

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'
like image 830
Tiutiu Avatar asked Oct 31 '25 14:10

Tiutiu


2 Answers

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);
}
like image 170
Rahul Avatar answered Nov 02 '25 05:11

Rahul


Simply put another parseFloat around, it will keep the decimal number :

parseFloat(parseFloat("9.55656").toFixed(2))

9.56
like image 39
Daphoque Avatar answered Nov 02 '25 05:11

Daphoque