开发者

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);


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)


Do you mean something like?

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜