0

var tm=110;
var fm=200;
var pr=Math.ceil(tm/fm*100);
console.log(pr);

The result is showing 56. But it should be 55

Note that tm/fm*100 is resulting 55.0000001 But When tm=100 and all fm=200 then the result is 50

I've solved that problem concedering upto 2 decimal places after point, I could not understand where from 1 is comming after some 0s!

Max
  • 965
  • 1
  • 10
  • 28
  • You have a typo. Correct method name is Math.ceil() – Sterling Beason Dec 11 '18 at 18:15
  • 1
    Because the closest binary representation of 110/200 which fits in the allowed memory for a floating point number is closer to .550...001 than to .550...000. You should round it to the appropriate number of significant digits. – James Dec 11 '18 at 18:18
  • 1
    In the future, please use titles that say something about the question. The current title, "Why the result is like this" is not helpful in determining what the question is about and thus makes it harder to find. See [ask]. – Heretic Monkey Dec 11 '18 at 21:50

1 Answers1

0

Math.ceil() returns the smallest integer greater than or equal to a given number. See MDN Documentation.

  1. Remove Math.ceil()
  2. parseFloat() pr variable
  3. Call Float's precision method toPrecision(8)

The extra 1 you are seeing is a result of binary floating point math. JavaScript does this. Source

<script>
    var tm=110;
    var fm=200;
    var pr= parseFloat(tm/fm*100);
    alert(pr.toPrecision(8)); // output: 55.00000000
</script>
Sterling Beason
  • 622
  • 6
  • 12