Timeline for How to round a number to n decimal places in Java
Current License: CC BY-SA 3.0
14 events
| when toggle format | what | by | license | comment | |
|---|---|---|---|---|---|
| Oct 1, 2024 at 14:13 | comment | added | Dmitry Kamenetsky | This should be the accepted answer, since precision is now variable. | |
| Nov 7, 2022 at 11:03 | comment | added | fillobotto | RoundingMode.HALF_UP is behaving like RoundingMode.HALF_DOWN on Android SDK 31 | |
| Nov 16, 2021 at 13:48 | comment | added | Niels Ferguson |
BigDecimal.ROUND_HALF_UP is deprecated since 9. You can use: RoundingMode.HALF_UP instead.
|
|
| May 19, 2021 at 9:16 | comment | added | Daniel F | There's a big trade off between accuracy and speed, as the method specified by @asterite is much faster, but rounds to errors. In cases where multiple calls to this method here consume 120 ms, the other method (multiply/divide) consumes mere 7 ms. So if you're just removing decimals in order to store a GPS bearing with only one decimal into a JSON string, you probably don't need all the precision of this expensive method. | |
| Mar 1, 2017 at 8:00 | history | edited | Nav | CC BY-SA 3.0 |
there was a need for a runnable sample program
|
| Aug 30, 2015 at 5:09 | comment | added | MetroidFan2002 | @ToolmakerSteve That's because using new BigDecimal with the double takes the double value directly and attempts to use that to create the BigDecimal, whereas when using BigDecimal.valueOf or the tostring form parses it to a string first (a more exact representation) before the conversion. | |
| Aug 28, 2015 at 3:41 | comment | added | ToolmakerSteve |
@Edd, interestingly, the rounding issue occurs in the case SebastiaanvandenBroek mentions in comment to asterite's answer. double val = 265.335;, BigDecimal.valueOf(val).setScale(decimals, BigDecimal.ROUND_HALF_UP).toPlainString(); => 265.34, but (new BigDecimal(val)).setScale(decimals, BigDecimal.ROUND_HALF_UP).toPlainString(); => 265.33.
|
|
| Jan 26, 2015 at 17:57 | comment | added | Edd |
Nice. Don't cut corners and use new BigDecimal(doubleVar) as you can run into issues with rounding of floating points
|
|
| S Feb 15, 2014 at 14:16 | history | suggested | user1685185 | CC BY-SA 3.0 |
code style jfc
|
| Feb 15, 2014 at 14:14 | review | Suggested edits | |||
| S Feb 15, 2014 at 14:16 | |||||
| Jul 12, 2011 at 0:20 | history | edited | MetroidFan2002 | CC BY-SA 3.0 |
toPlainString edit.
|
| Jun 30, 2011 at 9:42 | history | edited | Jonik | CC BY-SA 3.0 |
format
|
| Feb 9, 2010 at 10:59 | comment | added | Etienne Neveu | That's my preferred solution. Even shorter: BigDecimal.valueOf(doubleVar).setScale(yourScaleHere, BigDecimal.ROUND_HALF_UP); BigDecimal.valueOf(double val) actually calls Double.toString() under the hood ;) | |
| Sep 30, 2008 at 18:33 | history | answered | MetroidFan2002 | CC BY-SA 2.5 |