简体   繁体   中英

Java int multiply by float loss of precision

int totalSum = ids.length() * price;

length is int
price is float

I get this error:

error: possible loss of precision

how to multiply int by float correctly without losing precision?

Because you are getting result in int, which will ignore the values after decimal

try this

double totalSum = ids.length() * price;

Use BigDecimal.intvalue :

int i = new BigDecimal(ids.length).multiply(new BigDecimal(price)).intValue();

... or you can just cast the whole operation as int :

int totalSum = (int)(ids.length() * price);

Edit

As implied in comments, I'm making this explicit: casting as int or getting the int value will incur in a loss of precision.

Use Deepak's answer if you were just not sure about which type to pick (and accept his answer).

尝试这个:

float totalSum = (float) ids.length() * price;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM