armand
armand

Reputation: 703

javascript extra large negative exponent to decimal conversion

How would I get this negative large exponential number 6.849391775995509e-276 to 6.84 in javascript?

I'm getting back negative exponential numbers from an api which I would like to use a shortened version, to 2 decimal points, in my ui. If it matters, im using the number in a d3 chart rendering in react.

I have been trying some different techniques from the javascript doc sites but can not seem to get it to. Is using a library like Immutable.js an option? Any help would be greatly appreciated. All of the attempts in the code snippet which use the exponent notation return 0.00.

function financial(x) {
  return Number.parseFloat(x).toFixed(2);
}
console.log(financial(6.849391775995509e-276));
const num = 6.849391775995509e-276
console.log(num.toFixed(2));
const num2 = 6.84939;
console.log(num2.toFixed(2));

console.log(financial('6.849391775995509e-276'));

Upvotes: 1

Views: 969

Answers (2)

ninesalt
ninesalt

Reputation: 4354

Similar to Jonas' answer, however you want to wrap it in parseFloat() to get an actual number rather than a string.

const num = 6.849391775995509e-276
var newNum = parseFloat(num.toString().substr(0,4)) 
console.log(newNum)

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138257

 +num.toString().substr(0,3)

Just convert it to a string and take the first digits.

Upvotes: 2

Related Questions