Martin
Martin

Reputation: 7310

Java: Format double with decimals

In Objective C I have been using this code to format a value so that a value with zero decimals will be written without decimals and a value with decimals will be written with one decimal:

CGFloat value = 1.5;
return [NSString stringWithFormat:@"%.*f",(value != floor(value)),value];

//If value == 1.5 the output will be 1.5
//If value == 1.0 the output will be 1

I need to do the same thing for a double value in Java, I tried the following but that is not working:

return String.format("%.*f",(value != Math.floor(value)),value);

Upvotes: 1

Views: 1415

Answers (3)

dhblah
dhblah

Reputation: 10151

Not sure how to do it with String.format("..") method, but you can achieve the same using java.text.DecimalFormat; See this code sample:

import java.text.NumberFormat;
import java.text.DecimalFormat;
class Test {
public static void main(String... args) {
        NumberFormat formatter = new DecimalFormat();
        System.out.println(formatter.format(1.5));
        System.out.println(formatter.format(1.0));
   }
}

The output is 1.5 and 1 respectively.

Upvotes: 0

Adeel Ansari
Adeel Ansari

Reputation: 39897

Look at how to print a Double without commas. This will definitely provide you some idea.

Precisely, this will do

DecimalFormat.getInstance().format(1.5)
DecimalFormat.getInstance().format(1.0)

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533500

Do you mean something like?

return value == (long) value ? ""+(long) value : ""+value;

Upvotes: 0

Related Questions