Dane Muller Dane Muller - 7 months ago 24
Java Question

Making doubles use commas instead of dots without importing formatting

I need to make this outflow, inflow, storage, and capacity print out doubles with commas. There methods just call out a double number but they need to be printed out in with commas every 3rd number. I am not exactly sure how to implement it with methods.

Example:

getInflow()
returns a double value that needs to be printed as
123,456,789
instead of
123456789.0


public void print() {
System.out.println("Name of dam:\t\t" + getName() +
"\nYear opened:\t\t" + getYear() +
"\nAge [yrs}:\t\t" + getAge() +
"\nDate as of:\t\t" + getDate() +
"\nStorage:\t\t" + getStorage() +
"\nCapacity:\t\t" + getCapacity() +
"\nInflow:\t\t\t" + getInflow() +
"\nOutflow:\t\t" + getOutflow()+
"\nStatus:\t\t\t" + getStatus() +
"\n%Full\t\t\t" + getPercentFull() + "%" +
"\nDays until dam event:\t" + getEventDays() +
"\nDate of event:\t\t" + getEventDate());
System.out.println();
}

Answer

Because you have said in your desired answer "123456789.0 needs to shown as 123,456,789" I am assuming you don't care about the single decimal place.

Wrap it with Decimal formatter:

DecimalFormat formatter = new DecimalFormat("###,###");

// Now wrap each and every desiredmethod output like formatter.format(methodOutput())     
System.out.println("Name of dam:\t\t" + getName() +
                 "\nYear opened:\t\t" + getYear() +
                 "\nAge [yrs}:\t\t" + getAge() +
                 "\nDate as of:\t\t" + getDate() +
                 "\nStorage:\t\t" + getStorage() + 
                 "\nCapacity:\t\t" + getCapacity() + 
                 "\nInflow:\t\t\t" + formatter.format(getInflow()) + 
                 "\nOutflow:\t\t" + formatter.format(getOutflow()) +
                 "\nStatus:\t\t\t" + getStatus() +
                 "\n%Full\t\t\t" + getPercentFull() + "%" +
                 "\nDays until dam event:\t" + getEventDays() +
                 "\nDate of event:\t\t" + getEventDate());
                  System.out.println();

I didn't know which other ones you wanted, so only did for inFlow and outFlow. For reference - you can check https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

If you don't want to use Formatters, you can use plain String.format("%,.0f", yourDoubleValue)