2m935h
2m935h

Reputation: 21

Double multiplying with int issue

double temp = 64.1;
System.out.println("Result = " + (temp*1000));

The result would be:

Result = 64099.99999999999

But the actual result should be 64100

In case of Double data type

double a = ((temp * 1000) % (0.5 * 1000));
a=7.275957614183426E-12;

In case of casting it to float

((((float) temp) * 1000) % (0.5 * 1000));
a=0.0;

Why this behaviour?

Upvotes: 1

Views: 3724

Answers (4)

Lutaaya Huzaifah Idris
Lutaaya Huzaifah Idris

Reputation: 3990

Try this out

double temp = 64.1;
int x = 1000;
System.out.println("Answer :" + Math.round((temp*x))); 

Upvotes: -1

Maggie
Maggie

Reputation: 121

The double in Java represents floating point number. It has 64 bits value, which consist of:

  • Sign bit: 1 bit
  • Exponent: 11 bits
  • Significant precision: 53 bits (52 explicitly stored)

Source: https://en.wikipedia.org/wiki/Double-precision_floating-point_format

Unlike fixed point numbers (byte, int, long), floating point number can't always consistently return exact same representation of a number. That's the reason why you get the result 64099.99999999999 instead of 64100.

Use BigDecimal in Java in order to get better control of decimal places.

Source: https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html

Upvotes: 0

MatWdo
MatWdo

Reputation: 1740

Is a typical numeric problem with floating point numbers, when you multiple e.g. double * int.

First option use Math.round:

Math.round((temp*1000))

Second option use BigDecimal class:

 BigDecimal temp = BigDecimal.valueOf(64.1);
 BigDecimal thousand = BigDecimal.valueOf(1000);
 BigDecimal result = temp.multiply(thousand);

 //example how to extract int or double value 
 int intResult = result.intValue();
 double doubleResult = result.doubleValue();
 System.out.println("Result = " + result);

Upvotes: 4

Apoorv Karkare
Apoorv Karkare

Reputation: 89

I think you can use ceil() method of JAVA.

double temp = 64.1;

System.out.println("Result = " + Math.ceil(temp*1000));

I hope this helps.

Upvotes: 0

Related Questions