仅在需要时显示双精度的小数

时间:2012-08-06 10:23:44

标签: java android double decimal string-formatting

我遇到了双重(小数)这个问题 当double = 1.234567然后我使用String.format("%.3f", myString);
结果是1.234

但是当我的双倍是10 结果将是10,000
我希望这是10

他们是否可以说他只需要在“有用”时显示小数?

我看到一些关于此的帖子,但那是php或c#,找不到关于android / java的东西(也许我看起来不太好)。

希望你们能帮我解决这个问题。

编辑,现在我使用类似这样的内容:myString.replace(",000", "");
但我认为他们的代码更加“友好”。

3 个答案:

答案 0 :(得分:77)

带有#参数的DecimalFormat是要走的路:

public static void main(String[] args) {

        double d1 = 1.234567;
        double d2 = 2;
        NumberFormat nf = new DecimalFormat("##.###");
        System.out.println(nf.format(d1));
        System.out.println(nf.format(d2));
    }

将导致

1.235
2

答案 1 :(得分:2)

不要使用双打。你可能会失去一些精确度。这是一个通用功能。

public static double round(double unrounded, int precision, int roundingMode)
{
    BigDecimal bd = new BigDecimal(unrounded);
    BigDecimal rounded = bd.setScale(precision, roundingMode);
    return rounded.doubleValue();
}

您可以使用

进行调用
round(yourNumber, 3, BigDecimal.ROUND_HALF_UP);

“precision”是您想要的小数点数。

Copy from Here.

答案 2 :(得分:0)

试一试

double amount = 1.234567 ;
  NumberFormat formatter = new DecimalFormat("##.###");
  System.out.println("The Decimal Value is:"+formatter.format(amount));
相关问题