aspose file tools*
The moose likes Beginning Java and the fly likes Converting BigDecimal to long with rounding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Converting BigDecimal to long with rounding" Watch "Converting BigDecimal to long with rounding" New topic
Author

Converting BigDecimal to long with rounding

Janek Kowalski
Greenhorn

Joined: Jun 06, 2009
Posts: 3
Hello Everybody,

I have problem with converting BigDecimal value to long value but with rounding applied (HALF_UP). i.e:
I have BigDecimal:



After covering I'd like l to have value 13, so method longValue doesn't help.
I use following trick but I'm not happy about it, maybe there is better way to do this?



greetings
j.k.

Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19556
    
  16

Try rounding the BigDecimal first, then calling its longValue() method:
The rounding takes the precision (number of digits) minus the number of decimals. This may go wrong if the rounding adds a digit (e.g. from 99.5 to 100), but initial tests show no problem.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Till Stoschus
Greenhorn

Joined: May 28, 2009
Posts: 14
Hi Janek,

if you expect that the 1st decimal place should decide rounding, then this could be a solution:



Till
Janek Kowalski
Greenhorn

Joined: Jun 06, 2009
Posts: 3
Thank you very much .

Both solutions work fine.

greetings
j.k.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19556
    
  16

I would prefer Till's solution. It handles cases like the jump form 99.xx to 100 better.
Janek Kowalski
Greenhorn

Joined: Jun 06, 2009
Posts: 3
Rob Prime wrote:I would prefer Till's solution. It handles cases like the jump form 99.xx to 100 better.


I've chosen Till's solution because using this I create one object less (MathContext) but when I've changed rounding mode to HALF_UP in yours solution it worked pretty the same. (99.7 was converted to 100 properly). Perhaps I'm missing something.

greetings
j.k.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Converting BigDecimal to long with rounding
 
Similar Threads
Rounding using BigDecimal
What actual Double.toString(double d) does?
BigDecimal rounding problem
Lost precision when do number format
Class cast on Object Array