Marcos
Marcos

Reputation: 1265

Display Double as string ignoring decimal part when the value is a whole number

What's the simplest way to display a double as String but not showing the decimal part if the double value is a whole number?

For example,
If I have the double value 10.0 it would display only 10 (no decimal part), but if I have the double value 10.35 it would display the complete value 10.35.

Upvotes: 0

Views: 129

Answers (4)

Morchul
Morchul

Reputation: 2037

This works fine:

System.out.println(getString(4.53)); // 4.53
System.out.println(getString(4.0)); // 4

public String getString(double d){
    return (d % 1 == 0) ? String.valueOf((int) d) : String.valueOf(d);
}

Upvotes: 0

Lucas Oliveira
Lucas Oliveira

Reputation: 3477

Just use java.text.NumberFormat

Example:

    final NumberFormat numberFormat = NumberFormat.getInstance();
    System.out.println(numberFormat.format( 10.0d ));
    System.out.println(numberFormat.format( 10.35d ));

the output will be:

10

10,35

Upvotes: 2

Daisy Day
Daisy Day

Reputation: 688

double one = 1.00;
String stringNumber;
if (one % 1 == 0) {
    Integer intOne = (int) one;
    stringNumber = intOne.toString();
} else {
    stringNumber = String.valueOf(one);
}

Upvotes: 0

Andrea
Andrea

Reputation: 6123

I would use this approach:

// 1. Make sure to have dot instead of comma as a separator:
DecimalFormatSymbols symbol = new DecimalFormatSymbols(Locale.US);
// 2. Define max number of decimal places:
DecimalFormat df = new DecimalFormat("#.###", symbol);

// 3. Use it:
System.out.println(df.format(yourNumber));

Upvotes: 3

Related Questions