1

I am facing weird issue during rounding the value using javascript. Some of the value is not rounding in correct format.

var n =17.955 ;
var roundedPrice;
roundedPrice = Math.round(n*100)/100;
console.log(roundedPrice); // It returns 17.95 instead of 17.96

It is happening for some specific values like 16.955, 17.955, 18.955, 19.955. Except these values like 1.955, 12.955, 20.955, 27.955 ... This round function return correct values.

Edited : It is happening with 17.955 only. This returns correct result with 17.9555 ( 3 times 5).

Thanks in advance.

zed Blackbeard
  • 760
  • 12
  • 30
  • This is a duplicate. It has to do with the inexact nature of binary representation of float values. Note that this is an issue with numbers in almost all programming languages, not just JavaScript. – Jared Smith Jun 22 '17 at 14:12
  • 1
    The problem strats from n * 100, it returns a shaky floating point value ending in .4999999999999, where you expected it to be a solid .5 – Freeman Lambda Jun 22 '17 at 14:17
  • It is happening with 17.955 only. This returns correct result with 17.9555 ( 3 times 5) – zed Blackbeard Jun 22 '17 at 14:22
  • @FreemanLambda : Yes, you are right. But it is happening with only `17.955 and 17.455`. For example, If you run `17.355 * 100`, it will return `1735.5` – zed Blackbeard Jun 22 '17 at 15:32
  • I have fixed my issue by using `var a = n*100; roundedPrice = Math.round(a.toPrecision(10))/100`. Thanks for your all help guys. – zed Blackbeard Jun 23 '17 at 05:32

1 Answers1

-3

You can use either Math.ceil() to get the expected result.

Pritom
  • 1,294
  • 8
  • 19
  • 37
  • How to tell when to use `ceil` when `floor`? – Yury Tarabanko Jun 22 '17 at 14:16
  • It depends on your requirement, what do you exactly want, either ceil or floor. – Pritom Jun 22 '17 at 14:17
  • 1
    It seems OP wants to round using precise mathimatical way of doing it. You suggested him to use `ceil`. How would this help? – Yury Tarabanko Jun 22 '17 at 14:18
  • 2
    @Pritom Yury Tarabanko is trying to gently lead you to seeing why your answer is wrong. I'm more blunt. Your answer is wrong: the OP's problem is related to the inherent inaccuracy of representing arbitrary floating point numbers in two's complement binary format. It has nothing to do with picking `ceil` or `floor` over `round`. Which you should have figured out from reading the linked dupe before posting an answer. – Jared Smith Jun 22 '17 at 14:33
  • Its not ensured that a person always give an correct answer, but that not means that you have to put a negative vote, we have not same mentality. – Pritom Jun 22 '17 at 14:49
  • @YuryTarabanko : I got clue by your comment "precise" to fix my issue. – zed Blackbeard Jun 23 '17 at 05:34