Git.Coach
Git.Coach

Reputation: 3092

How to round a number bigger than long type max value in Java?

I've to handle really big double values and I have to round them to the next full number. If I round the double value I always receive the value 9.223372036854776E18 which happens to be the maximum long value. How do I round values bigger than this?

Edit: Just for clarification: I'm not a Java programmer and come from the C front. I'm helping a friend on this case. I tried unsigned (obviously didn't work), googled and found BigDecimal and BigInteger. Tried casting them and it happened to crash. That's why I came here. Thanks for helping me!

Upvotes: 1

Views: 1675

Answers (5)

Louis Wasserman
Louis Wasserman

Reputation: 198211

Any double value too large to fit into a long already represents an integer value, and rounding it will have no effect. This is because a double only holds 52 bits of precision on its significand, and a long holds 64 -- so if the value is too big for a long, the double doesn't have enough precision left to hold any fractional parts.

Upvotes: 2

user207421
user207421

Reputation: 310985

In essence:

Math.floor(d+0.5)

but you have to adjust to subtraction if d is negative.

Upvotes: 3

Mitch Wheat
Mitch Wheat

Reputation: 300719

Use BigDecimal

e.g.

BigDecimal decimalA = new BigDecimal("98765432123456789");

Upvotes: 2

Cory Kendall
Cory Kendall

Reputation: 7314

BigDecimal can hold any double and float value. To convert from a double to a BigDecimal, use code like this:

double reallyBigDouble
BigDecimal x = new BigDecimal(reallyBigDouble);

To round to the nearest integer value, you could use code like this:

BigDecimal roundedToInteger = x.round(new MathContext(MathContext.UNLIMITED));

Upvotes: 2

kosa
kosa

Reputation: 66657

BigDecimal would be the solution to contain values larger than long.

Read this BigDecimal javadoc

You need to instantiate BigDecimal(yourDoubleValue); not casting.

Upvotes: 5

Related Questions