user13378232
user13378232

Reputation:

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?

Upvotes: 0

Views: 147

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201507

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

Upvotes: 0

Eklavya
Eklavya

Reputation: 18480

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

x = Math.floor(x + 0.4);

Upvotes: 5

Related Questions