Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate a BigDecimal without rounding

After a series of calculations in my code, I have a BigDecimal with value 0.01954

I then need to multiply this BigDecimal by 100 and I wish the calculated value to be 1.95

I do not wish to perform any rounding up or down, I just want any values beyond two decimal places to be truncated

I tried setting scale to 2, but then I got an ArithmeticException saying rounding is necessary. How can I set scale without specifying rounding?

like image 621
DJ180 Avatar asked Jun 17 '14 20:06

DJ180


People also ask

How do I truncate without rounding?

To get rid of some decimal places without and rounding, use TRUNC(), which is short of truncate. It takes two arguments: the value and the number of decimal places. Whatever is to the right of the specified decimal location is simply discarded. For example, =TRUNC(12.119999, 2) evaluates to 12.11.

How do you truncate a large decimal?

5555555 as the truncating value is > 0.5 so it will round to x. 56 if you use BigDecimal newValue = myBigDecimal. setScale(2, RoundingMode.

How do you round BigDecimal to zero decimal places?

You can use setScale() to reduce the number of fractional digits to zero. Assuming value holds the value to be rounded: BigDecimal scaled = value. setScale(0, RoundingMode.


1 Answers

Use either RoundingMode.DOWN or RoundingMode.FLOOR.

BigDecimal newValue = myBigDecimal.setScale(2, RoundingMode.DOWN); 
like image 192
GriffeyDog Avatar answered Sep 24 '22 04:09

GriffeyDog