简体   繁体   English

Java int乘以浮点精度损失

[英]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? 如何正确地将int乘以float而不丢失精度?

Because you are getting result in int, which will ignore the values after decimal 因为您正在获取int结果,所以它将忽略小数点后的值

try this 尝试这个

double totalSum = ids.length() * price;

Use BigDecimal.intvalue : 使用BigDecimal.intvalue

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

... or you can just cast the whole operation as int : ...或者您可以将整个操作转换为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. 正如注释中所隐含的那样,我在此明确指出:强制转换为int或获取int值将导致精度下降。

Use Deepak's answer if you were just not sure about which type to pick (and accept his answer). 如果您不确定要选择哪种类型(并接受他的答案),请使用Deepak的答案。

尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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