How can I verify how many decimals a number has in Java?
I need to calculate PI to a certain number of decimal, and I want to know how I can stop my loop when I reach the desired decimals number?
How can I verify how many decimals a number has in Java?
I need to calculate PI to a certain number of decimal, and I want to know how I can stop my loop when I reach the desired decimals number?
You can't check the number of decimals on a double
directly, but you can convert it to a String
using String str = number + "";
and then check str.length
.
If you use BigDecimal for your calculation you could set the scale to the desired value.
If you only need a small precision e.g. 15 decimal places, you can use double for that. To specify the number of digits you could use Math.pow(10, -decimalPlaces) to calculate the smallest allowed deviation.
1) you firstly convert it to string
2)Then take a substring from '.' to end
3) Thenget the length of this substring