Search code examples
javadoubledigits

Creating 0.000.. with certain decimals


I am trying to create the number 0.00000.... with as many '0' as the user input wants. What is wrong with my code below?

      int n;
      double dec = 0.0;

   in = new Scanner(System.in);
        n = in.nextInt();

    for (i = 1; i <= n; i++) 
                dec = dec / 10.0d;

Number doesn't change.


Solution

  • You're expecting double to retain the number of decimal digits - it doesn't do that. The value is always normalized. The double type is all about the magnitude of a number, not a particular decimal representation. It's suitable for naturally occurring quantities - weights, heights etc.

    If you care about decimal digits, then BigDecimal is a more suitable type for you. This is more appropriate for currency values for example, where there really is a precise amount specified as a decimal representation.

    BigDecimal does retain the number of decimal digits you use, but you'll need to be careful about exactly how you use it. You'll no doubt find the setScale method useful.

    For example:

    import java.math.BigDecimal;
    
    class Test {
        public static void main(String[] args) throws Exception {
            BigDecimal x = new BigDecimal("0")
            System.out.println(x); // 0
            x = x.setScale(5);
            System.out.println(x); // 0.00000
        }
    }