Java 将双精度转换为没有小数位的字符串的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28707098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 06:40:41  来源:igfitidea点击:

Best way to convert a double to String without decimal places

javamath

提问by John Alexander Betts

What is the best way to convert a double to String without decimal places?

将double转换为没有小数位的String的最佳方法是什么?

What about String.valueOf((int) documentNumber)?

关于什么 String.valueOf((int) documentNumber)?

The doubles always have 0 after the decimal dot. I don't need to round or truncate

双打总是在小数点后为 0。我不需要舍入或截断

采纳答案by Paco Abato

If you are sure that the double is indeed an integer use this one:

如果您确定 double 确实是一个整数,请使用这个:

NumberFormat nf = DecimalFormat.getInstance();
nf.setMaximumFractionDigits(0);
String str = nf.format(documentNumber);

As a bonus, this way you keep your locale's configuration as in thousand separator.

作为奖励,通过这种方式,您可以将语言环境的配置保持为千位分隔符。

EDIT
I add this previously removed option as it seems that was useful to the OP:

编辑
我添加了这个以前删除的选项,因为它似乎对 OP 有用:

Double.valueOf(documentNumber).intValue();

回答by Hann

You can convert a double to string with the minimum necessary precision:

您可以将 double 转换为具有最低必要精度的字符串:

public static String ceonvert(double d)
{
    if(d == (long) d)
        return String.format("%d",(long)d);
    else
        return String.format("%s",d);
}

Or this :

或这个 :

> new DecimalFormat("#.##").format(2.199); //"2.2"

回答by kuki

You could try this:

你可以试试这个:

String numWihoutDecimal = String.valueOf(documentNumber).split("\.")[0];

回答by Piotr Zych

I'm not sure if this is best way, but i'am sure it's shortest way:

我不确定这是否是最好的方法,但我确定这是最短的方法:

((int)documentNumber) + ""

回答by Kirby

Given the newly edited question stating that the doubles are in fact integers, I'd say that your suggested answer String.valueOf((int) documentNumber)is great.

鉴于新编辑的问题说明双打实际上是整数,我会说您建议的答案String.valueOf((int) documentNumber)很棒。

回答by Padroniza??o S A

Quotation Marks + Double

引号 + 双

String s = "" + 0.07;

字符串 s = "" + 0.07;

LOL this is the best way, (obviously for experienced programmers)!

大声笑这是最好的方法,(显然对于有经验的程序员)!

回答by Varun Joshi

The easiest way to convert a double to string is to use quotation marks and then the double after that. double d = 123; String a = "" + d;

将 double 转换为 string 的最简单方法是使用引号,然后使用双引号。双 d = 123; 字符串 a = "" + d;

Another way is to use the toString method if you want to keep the way you converted it hidden

另一种方法是使用 toString 方法,如果你想保持你转换它的方式隐藏

public String toString()
{
   String a + ""  d;
}