I want to round a given decimal to a number of decimal places that varies depending on user input. The other methods I know of (like BigDecimal
or String.format
) work with a fixed number of decimal places to round to. How do I round to a variable number of decimal places instead?
Asked
Active
Viewed 192 times
-1

user3263023
- 1
- 1
-
what do you mean by variable number of decimal place? – Parth Soni Feb 03 '14 at 05:26
-
If the user specifies five places, it will round to five places - if the user specifies two, it will round to that, etc. – user3263023 Feb 03 '14 at 05:31
-
`BigDecimal.round()` takes a MathContext argument which is constructed with an `int setPrecision` *variable.* So what's your question? – user207421 Feb 03 '14 at 05:34
-
I apologize, it seems like I hadn't quite understood how to use BigDecimal. However, the code `BigDecimal bd = new BigDecimal(num).setScale(numOfDecPlaces, BigDecimal.ROUND_HALF_UP);` works differently for even and odd numbers - 0.5595 is rounded to 0.559, when rounding to three decimal places. How can I get it to become 0.600? – user3263023 Feb 03 '14 at 06:16
1 Answers
-1
You can use powers.
double mask = Math.pow(10, digits);
double result = Math.round(number * mask) / mask;
However, this method will not act well with larger numbers.
EDIT:
BigDecimal
also has setScale
. Provide the number of digits you require in the decimal part.

hsun324
- 549
- 3
- 9
-
'not act well with larger numbers' ... or smaller ones, or indeed work reliably at all. – user207421 Feb 03 '14 at 05:32