Home:ALL Converter>How to truncate a BigDecimal without rounding

How to truncate a BigDecimal without rounding

Ask Time:2014-06-18T04:36:50         Author:DJ180

Json Formatter

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?

Author:DJ180,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/24272849/how-to-truncate-a-bigdecimal-without-rounding
GriffeyDog :

Use either RoundingMode.DOWN or RoundingMode.FLOOR.\n\nBigDecimal newValue = myBigDecimal.setScale(2, RoundingMode.DOWN);\n",
2014-06-17T20:41:44
user1676075 :

Use the setScale override that includes RoundingMode:\n\nvalue.setScale(2, RoundingMode.DOWN);\n",
2014-06-17T20:41:07
maheeka :

I faced an issue truncating when I was using one BigDecimal to set another. The source could have any value with different decimal values.\nBigDecimal source = BigDecimal.valueOf(11.23); // could 11 11.2 11.234 11.20 etc\n\nIn order to truncate and scale this correctly for two decimals, I had to use the string value of the source instead of the BigDecimal or double value.\nnew BigDecimal(source.toPlainString()).setScale(2, RoundingMode.FLOOR))\n\nI used this for currency and this always results in values with 2 decimal places.\n\n11 -> 11.00\n11.2 -> 11.20\n11.234 -> 11.23\n11.238 -> 11.23\n11.20 -> 11.20\n",
2020-07-24T04:50:55
teja :

\nBigDecimal.valueOf(7.777)\n.setScale(2, RoundingMode.DOWN)\n.stripTrailingZeros()\n\nResult: 7.77\n\nBigDecimal.valueOf(7.7)\n.setScale(2, RoundingMode.DOWN)\n.stripTrailingZeros()\n\nResult: 7.7\n\nBigDecimal.valueOf(77)\n.setScale(2, RoundingMode.DOWN)\n.stripTrailingZeros()\n\nResult: 77",
2022-08-10T19:21:42
yy