Reputation: 1265
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
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
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
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
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