2

I'm taking a number, dividing by 100 and then multiplying it by 100 to have it return to it's original value. Some returned values are a little off however.

var num = 57,
    num = num / 100,

    // this should return the number to the original
    // however in this example it returns 56.99999999999999
    num = num * 100;

Here's a fiddle: http://jsfiddle.net/njsdW/

In truth, all I want to do is add two 0's in front of the number, but I'm not always sure where the decimal would be.

EDIT: My solution:

var num = 57,
    num = (parseFloat((num / 100).toPrecision(15)));

    // this should return the number to the original
    num = (parseFloat((num * 100).toPrecision(15)));
ditto
  • 5,917
  • 10
  • 51
  • 88
  • this is a product of inaccuracies in [IEEE 754](http://en.wikipedia.org/wiki/IEEE_754) computations – Janus Troelsen Jan 21 '13 at 11:06
  • 2
    http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken – georg Jan 21 '13 at 11:07
  • Anything involving floating point math with normal floats is a cause for grief. Most languages have special libraries for dealing with precision in floats, eg. BigDecimal in Ruby and Java. – sevenseacat Jan 21 '13 at 11:07
  • *" all I want to do is add two 0's in front of the number"*... Since this is your actual problem, could you elaborate on this please? Some example input and output would be helpful. – Felix Kling Jan 21 '13 at 11:15
  • @Felix Kling, divide by 100. In theory that'll just mean placing two 00's in front of the number. – ditto Jan 21 '13 at 11:23
  • @Chaplin: `100` divided by `100` is `1`. Number values don't have a concept of *leading zeros*. You can **format** your number to have leading zeros, but that's something totally different. – Felix Kling Jan 21 '13 at 11:26
  • +1 for providing jsfiddle – Olaf Dietsche Jan 21 '13 at 11:39

2 Answers2

1

You must save the precision of your number and restore it after dividing by 100

prec = num.length;

// adjust for decimal point
if (num.indexOf('.') != -1)
    prec--;

// adjust for leading zero
if (num < 1)
    prec--;

num /= 100;
self.find('h2').append(num.toPrecision(prec));

JSFiddle

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198
0

You can use a JavaScript bignum implementation like javascript-bignum or gmp.js to get arbitrary precision. If you want to use gmp.js, you'd have to rewrite your application in C/C++ or write gmp.js bindings for JavaScript. In return, you'd get the battle-tested reliability and optimal algorithmic effenciency from GNU GMP.

Janus Troelsen
  • 20,267
  • 14
  • 135
  • 196