PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 12, 2022

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

 August 12, 2022     decimal, double, javascript     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing