Friday, August 12, 2022

[FIXED] How to add values in javascript when converting from string

Issue

I have a string that I try to convert to a decimal number with 16 decimals. Then I like to add that number to the number 0 which should be:

30280.9529335

But I get: 030280.9529335

How do you properly do this in javascript?

var totalnumber = 0; var str = "30280.9529335";
totalnumber = totalnumber + ConvertToDouble(str);

console.log(totalnumber); //030280.9529335

function ConvertToDouble(x) {
    return Number.parseFloat(x).toFixed(16);
}


Solution

Well your problem is placement of toFixed, toFixed return String not number

console.log(typeof (1).toFixed(2))

So here your ConvertToDouble function returns string and 0 + some numeric string will act as concatenation not addition

var totalnumber = 0; var str = "30280.9529335";
totalnumber = totalnumber + ConvertToDouble(str);

console.log(totalnumber.toFixed(16)); //030280.9529335

function ConvertToDouble(x) {
    return Number.parseFloat(x)
}



Answered By - Code Maniac
Answer Checked By - Pedro (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.