简体   繁体   中英

Getting unexpected results when multiply float with the number

I get unexpected results in my currency converter. Here is the relevant code:

val = Float.parseFloat(values);

us=val*0.27f;
usa.setText(Float.toString(us));

pk=val=26.95f*val;
pak.setText(Float.toString(pk));

u=val*0.16f;
uk.setText(Float.toString(u));

om=val*0.10f;
oman.setText(Float.toString(om));

ks=val*1.02f;
ksa.setText(Float.toString(ks));

e=val*0.20f;
eu.setText(Float.toString(e)

I get:

us=0.27
e=0.2
uk=0.16
ksa=1.02
oman=2.69
pak=26.95

The oman -value is not correct. Why?

Here:

pk=val=26.95f*val;

you overwrite val value. remove val= and it should work fine.

pk=val=26.95f*val; overwiting..

您知道Float.parseFloat的参数类型是String吗?实际上parseFloat方法用于将String解析为Float,但是您在注释中说所有变量都是float!

Float, Double, float, double are not accurate in java. For example:

double number1 = 0.58 * 100;    
System.out.println("" + number1);

and the output is 57.99999999999999 not 58 as expected. BigDecimal class can be used instead for accurate performance.

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