Question

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.

Was it helpful?

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
    }
}

OTHER TIPS

If you just want to display the decimal point according to user input, Try

int n;
double dec = 0.0;

in = new Scanner(System.in);
n = in.nextInt(); //number of decimal places

System.out.println(String.format("%."+n+"f",dec));

0.0, 0.00, 0.0000000000000000000000000000000000000000000000 and so on are exactly the same value; Java literally can't tell them apart during runtime. No matter how many times you divide it by 10, it will remain EXACTLY the same number.

When being printed, trailing zero digits are omitted (unless explicitly specified in, for instance, String.format).

Basically, what you are trying to do is keep on dividing 0.0. But it'll always give you the same result as Java considers 0.000 as 0.0. Even 0.0000000000000000 will be considered as 0.0. If you just want to display that many 0s, then save it in a String and then display.

...
StringBuilder s = new StringBuilder("0.");
for(int i = 1; i < n; i++)
    s.append("0");
String num = s.toString();
//Then use it.

If you need string with user defined '0':

public static String FormatZero( int accurancy_ ) throws IllegalArgumentException
{
    if( 0 >= accurancy_ )
    {
        throw new IllegalArgumentException( "accurancy_must be > 0" );

    }

    String  formatString    = "0.";

    for( int i = 0 ; i < accurancy_ ; ++i )
    {
        formatString    += "0";

    }

    DecimalFormat   format  = new DecimalFormat( formatString );
    String      result  = format.format( 0d );

    return result;

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top