简体   繁体   中英

How do i Round Values Properly in Java?

I want to get the round values as shown below.

round (1.4) = 1
round (1.5) = 1
round (1.6) = 2

How do i get result of round (1.5) to 1 instead of 2 using java code?

Since you want from .6 it will be ceiling the value then use this

x = Math.floor(x + 0.4);

As I mentioned in the comments, you can subtract 0.1 before calling Math.round . Like,

DoubleStream.of(1.4, 1.5, 1.59, 1.6)
        .mapToInt(x -> (int) Math.round(x - 0.1))
        .forEach(System.out::println);

Outputs (as requested)

1
1
1
2

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