0

Is there any better way other than

Math.round(0.2+0.4) = 0.6

Actually, I have a series of index 0, 0.02, 0.04, 0.06, 0.08, 0.10 ---- I have to convert it to Array Index 0,1,2,3,4,5-- by dividing by 0.02

JavaScript provides

 0.28/0.02 = 14.000000000000002

I solve this problem by Math.round(0.28/0.02). I am curious is there any other or better way to solve this problem

Jhankar Mahbub
  • 9,234
  • 9
  • 45
  • 50

2 Answers2

2

JS Number class is 64-bit floating-point, so it's bound to lose precision in corner cases like this one (also for integers > 2^53).

It's OK to use Math.round and their friends in your case. For a full discussion of the problem and possible workarounds, see the article provided by @Bergi.

Community
  • 1
  • 1
LexLythius
  • 1,824
  • 1
  • 12
  • 18
1

I wonder isn't that easier in your particular case to precache the hash of indexes, like this:

var fpIndexes = ['0', '0.02', '0.04', '0.06'];
var fpIndexesHash = {};
for (var i = 0, l = fpIndexes.length; i < l; i++) {
  fpIndexesHash[fpIndexes[i]] = i;
}

Then you'll be able to get the integer index out of floating-point value without doing Math.round:

someValues[fpIndexesHash['0.02']]; // the same as someValues[1];

I've used strings here, but I actually think plain floating-point literals can be used here too: my understanding is that a specific floating-point literal will never be represented by different IEEE-754 values at the same machine during the lifetime of a script.

So even if 0.06 literal is actually represented as 0.060000001 number in memory, it'll be uniform - and will be converted to the same string value both in fpIndexesHash assigning round and in the interpreting one.

raina77ow
  • 91,589
  • 12
  • 180
  • 210