Java: Format double with decimals

岁酱吖の 提交于 2019-12-24 09:49:12

问题


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

回答1:


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)



回答2:


Do you mean something like?

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



回答3:


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.



来源:https://stackoverflow.com/questions/5895338/java-format-double-with-decimals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!