yasarui
yasarui

Reputation: 6563

javascript toFixed not working in my calculations

Hi guys I have bytes say 007458415820874584158208042423283712.I want to convert this into GB, so tried to divide it by 1048576 i am getting a result of 7.112899609446129e+27. I want only the two numbers after the decimal point, so I have used .toFixed like below. It doesn't work, I am getting the same response as if I have not used the toFixed function. I just want the result to be just 7.1. help me out on this.

   console.log((007458415820874584158208042423283712/1048576).toFixed(2));

Upvotes: 1

Views: 206

Answers (2)

Krutika Patel
Krutika Patel

Reputation: 430

You can use this prototype function for your solution.

Number.prototype.toFixedSpecial = function(n) {
  var str = this.toFixed(n);
  if (str.indexOf('e+') === -1)
    return str;

  // if number is in scientific notation, pick (b)ase and (p)ower
  str = str.replace('.', '').split('e+').reduce(function(p, b) {
    return p + Array(b - p.length + 2).join(0);
  });
  
  if (n > 0)
    str += '.' + Array(n + 1).join(0);
  
  return str;
};
var val = (007458415820874584158208042423283712/1048576);
console.log(val);
console.log(val.toFixedSpecial(2))           //"7112899609446129000000000000.00"
console.log( 1e21.toFixedSpecial(2) );       // "1000000000000000000000.00"
console.log( 2.1e24.toFixedSpecial(0) );     // "2100000000000000000000000"
console.log( 1234567..toFixedSpecial(1) );   // "1234567.0"
console.log( 1234567.89.toFixedSpecial(3) ); // "1234567.890"

Upvotes: 4

lbragile
lbragile

Reputation: 8122

Your problem is that this is scientific notation and toFixed() supports 20 decimal places. Your number is 7.112899609446129e+27 which technically (most likely) has decimal places but they are not visible due to scientific notation.

The solution would be to use toExponential() like so:

parseFloat((7458415820874584158208042423283712/1048576.0).toExponential(2))

Output: 7.11e+27

A more correct way is shown here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential

But this gives "7.11e+27" (a string)

If you just want 7.11 then you can use slice(0,3) as follows:

var result_str = (7458415820874584158208042423283712/1048576).toExponential(2);
console.log(parseFloat(result_str.slice(0,3)));

Result: 7.1

Upvotes: 3

Related Questions