1

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?

Pratik
  • 11,183
  • 7
  • 34
  • 72
user2997779
  • 277
  • 1
  • 16

4 Answers4

1

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.

Warlord
  • 2,760
  • 15
  • 21
0

If you use BigDecimal for your calculation you could set the scale to the desired value.

nitnamby
  • 374
  • 1
  • 8
0

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.

SpiderPig
  • 7,899
  • 2
  • 18
  • 36
0

1) you firstly convert it to string

2)Then take a substring from '.' to end

3) Thenget the length of this substring

TruePS
  • 483
  • 2
  • 11
  • 33