• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Tim Holloway
  • Carey Brown
  • salvin francis

Converting BigDecimal to long with rounding

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Sheriff
Posts: 21788
104
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Janek,

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



Till
 
Janek Kowalski
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much .

Both solutions work fine.

greetings
j.k.
 
Rob Spoor
Sheriff
Posts: 21788
104
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would prefer Till's solution. It handles cases like the jump form 99.xx to 100 better.
 
Janek Kowalski
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
Well don't expect me to do the dishes! This ad has been cleaned for your convenience:
Enterprise-grade Excel API for Java
https://products.aspose.com/cells/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!