Yevgeny Simkin
Yevgeny Simkin

Reputation: 28349

How do I compare floating point numbers

Please forgive the obvious "I should probably already know this" element to the question but I'm not seeing a method that I would run the division side of this evaluation through, to get the result to come back as true.

I'm looking for a function that would return the result as a float of specific precision, so that the following would work...

float a = 0.66;

if( magicPrecisionFunction(2.0f/3.0f , 2) == a){ //the 2 specifies the level of precision
   //something
}

I realize that I can write this myself in 2 minutes, but I was hoping to find a Java native way to do this "properly".

Upvotes: 0

Views: 200

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533520

If you want precision I wouldn't use float as double is simpler to write and gives you half a trillion times the accuracy.

Similar to @rofl's example

int n = 2, d = 3;
if ((long)(100.0 * n / d) == 66) {
  ...
}

Not only is this about 100x faster than using BigDecimal, the code is shorter to write.

BTW The proper way to to convert a double to a BigDecimal is to use valueOf

BigDecimal bd = BigDecimal.valueOf(0.1);
System.out.println(bd); // prints 0.1

Upvotes: 2

Dima
Dima

Reputation: 8652

you can use BigDecimal, it will do exactly what you need, you can create the number you need and set the precision with MathContext

    BigDecimal b1 = new BigDecimal("2.0");
    BigDecimal b2 = new BigDecimal("3.0");
    BigDecimal ans = b1.divide(b2, new MathContext(2)); // 2 is precision

Upvotes: 1

rolfl
rolfl

Reputation: 17707

how abut...

if (Math.round(100.0f * 2.0f/3.0f) == 66) {
  ..
}

EDIT: Ahhh... missed the point... not round, but truncatte. in which case:

if ((int)(100.0f * 2.0f / 3.0f) == 66) {
  ...
}

Upvotes: 1

Related Questions