user2113442
user2113442

Reputation: 35

Java Programming - Need to insert commas

I'm just starting to learn java and need help with the basics. I wrote code that converts light speed to kilometers per second. The code looks like this:

public class LightSpeed
{
    private double conversion;

    /**
     * Constructor for objects of class LightSpeed
     */
    public LightSpeed()
    {
        conversion = (186000 * 1.6); //186000 is miles per second and 1.6 is kilometers per mile
    }

    /**
     * Print the conversion
     */
    public void conversion()
    {
        System.out.println("The speed of light is equal to " + conversion + " kilometers per second");
    }
}

I need the conversion to have commas in it so the number doesn't all run together. instead of the number looking like 297600.0 I need it to look like 297,600.0. Someone please help! Thank you

Upvotes: 0

Views: 266

Answers (2)

rgettman
rgettman

Reputation: 178253

You need to format the number. One of the ways is with DecimalFormat in java.text.

DecimalFormat df = new DecimalFormat("#,##0.0");
System.out.println("The speed of light is equal to " + df.format(conversion) + " kilometers per second");

Another way is with printf. Use the comma flag and output one digit past the decimal point. Here's more about the flags for printf.

System.out.printf("The speed of light is equal to %,.1f kilometers per second\n", speed);

Upvotes: 2

Jayamohan
Jayamohan

Reputation: 12924

Change your conversion method to

/**
 * Print the conversion
 */
public void conversion() {
    DecimalFormat myFormatter = new DecimalFormat("###,###.##");
    System.out.println("The speed of light is equal to "
            + myFormatter.format(conversion)
            + " kilometers per second");
}

Upvotes: 0

Related Questions