Gracie williams
Gracie williams

Reputation: 1145

toFixed function on large numbers

I have following number with e+ on it

9.074701047887939e+304

I want to take only 9.07

So I tried below , but its not working , its returning full output

console.log(parseFloat(9.074701047887939e+304).toFixed(2));

Ps : I also need the code to work for normal numbers aswell for example 892.0747010 , should output 892.07

Upvotes: 1

Views: 1248

Answers (2)

nonopolarity
nonopolarity

Reputation: 151036

Since you mentioned for both 9.074701047887939e+304 and 9.074701047887939, you want the answer to be 9.07.

For 9.074701047887939e-304 I assume you want 9.07 too, although you might actually want 0.00.

const twoDecimal = (a =>
  (a.toString().match(/e/) ? Number(a.toString().match(/[^e]*/)[0]) : a).toFixed(2)
);

console.log(twoDecimal(9.074701047887939e+304));
console.log(twoDecimal(9.074701047887939e-304));
console.log(twoDecimal(9.074701047887939));
console.log(twoDecimal(789.074701047887939));
console.log(twoDecimal(0.00001));
console.log(twoDecimal(0.20001));

console.log(twoDecimal(-9.074701047887939e+304));
console.log(twoDecimal(-9.074701047887939e-304));
console.log(twoDecimal(-9.074701047887939));
console.log(twoDecimal(-789.074701047887939));
console.log(twoDecimal(-0.00001));
console.log(twoDecimal(-0.20001));

console.log(twoDecimal(0));

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370779

toFixed trims digits after the decimal point, but your actual number is very large - it doesn't have a decimal point.

If you don't know in advance whether the number is large or not, one option is to call toFixed(2) on the number first (trimming off and properly rounding digits past the decimal point for small numbers), then using a regular expression to take the numeric part only (removing the e if it exists), then call toFixed(2) again (trimming off and properly rounding digits past the decimal point for large numbers):

const fix = num => Number(
  num.toFixed(2).match(/\d+(?:\.\d+)?/)[0]
).toFixed(2);

console.log(fix(9.074701047887939e+304));
console.log(fix(123.4567));
console.log(fix(12345));

Upvotes: 3

Related Questions