简体   繁体   中英

Rounding has unexpected results in Java

I was surprised when I run this code:

int  x = (int)4.9f;
System.out.println(x);

Why is the result 4 and not 5?

It's because you're not rounding, but casting a float as integer. Casting simply removes the decimal part. If you want to round, you must use

double x = 4.9f;
System.out.println(Math.round(x));

Also, if you want to use explicit upper or lower rounding, you should use Math.ceil(x) or Math.floor(x) instead.

Using a cast simply truncates the value rather than performing proper rounding. You can use Math.round to get a correctly rounded value, or BigDecimal for a choice of 8 different rounding modes.

When (int)4.9f is used, it will simply truncate the decimal values (no rounding!). For rounding, you need to use Math.round() function.

You are using an int and int cant hold decimal numbers as you are casting a float to int so it removes the digit after the decimal..

int  x = (int)4.9f;
System.out.println(x);

So use

double x = 4.9f 

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