-2
var coeff='0.1';
var amount='12.2';

var res = Math.floor(parseFloat(amount) / parseFloat(coeff));

console.log(res);

Why the result of this is 121 (I was expecting 122)?

EDIT: my question was ambiguous: no trouble with the floor function. I was just wondering why 12.2 / 0.1 is not equal to 122.

Cœur
  • 37,241
  • 25
  • 195
  • 267
David Dahan
  • 10,576
  • 11
  • 64
  • 137

1 Answers1

0

the result is 121.99999999999999

from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor

The Math.floor() function returns the largest integer less than or equal to a given number.

so it cuts off the .99999. you might want to use

Math.round(parseFloat(amount) / parseFloat(coeff));

instead

Jesse
  • 1,262
  • 1
  • 9
  • 19
  • 3
    explain the 121.99999999 instead of 122.0 (12.2 / 0.1 is 122 after all) – Jaromanda X Sep 08 '15 at 14:35
  • @JaromandaX From what I understand, javascript has a weird usage of bytes in your system. Don't ask me why though – Timberman Oct 23 '22 at 16:32
  • @Timberman, there's no weird usage of bytes in my system by javascript or anything else. 7 years ago, I was pointing out that the answer did not fully answer the question - sure, it's obvious that `Math.floor(121.99999)` is `121` - everyone knows that, but why would the result of `12.2/0.1` be 121.99999 in the first place – Jaromanda X Oct 23 '22 at 22:12