Convert Double to String, Removing Decimal Places – 将双数转换为字符串,去掉小数位

最后修改: 2018年 9月 15日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

In this tutorial, we’ll take a look at the different ways to convert a double value to a String, removing its decimal places.

在本教程中,我们将看看double值转换为String的不同方法,去除其小数位。

We’ll look at how to do it when we want to just truncate the decimal part and when we want to round it.

我们将看看当我们想只截断小数部分和想四舍五入时如何做。

2. Truncation Using Casting

2.使用铸造的截断法

If our double value is within the int range, we can cast it to an intThe cast truncates the decimal part, meaning that it cuts it off without doing any rounding.

如果我们的double值在int范围内,我们可以将其转换为int这种转换会截断小数部分,也就是说,它在不做任何四舍五入的情况下将其切断。

This approach is about 10 times as fast as the other approaches we’ll look at.

这种方法的速度大约是我们要看的其他方法的10倍。

Once it’s an int, then we can then pass it to the valueOf method on the String class:

一旦它是一个int,,那么我们就可以把它传递给valueOf方法 String类上

String truncated = String.valueOf((int) doubleValue);

We can confidently use this approach when we’re guaranteed that the double value is within the range of an int. But if our value exceeds that, casting won’t work like we’d want.

当我们保证双倍值在int的范围内时,我们可以放心地使用这种方法。但是,如果我们的值超过了这个范围,铸造就不会像我们希望的那样工作

3. Rounding Using String.format()

3.使用String.format()进行舍入

Now, the remaining approaches aren’t as limited as casting, but they have their own nuances.

现在,其余的方法并不像铸造那样有限,但它们有自己的细微差别。

For example, another approach is to use the format method of the String class. The first parameter of the method specifies that we are formatting a floating point value with zero digits after the decimal point:

例如,另一种方法是使用format类的String方法。该方法的第一个参数指定我们要格式化一个小数点后为零的浮点值。

String rounded = String.format("%.0f", doubleValue);

The format method uses HALF_UP rounding which will round up if the value after the fractional part is .5 or above. Otherwise, it returns the number before the decimal point.

format方法使用HALF_UP四舍五入,如果小数部分之后的数值是0.5或以上,它将向上舍入。否则,它会返回小数点之前的数字。

And while simple, String.format is the slowest way to do this.

虽然很简单,但String.format 是最慢的方法

4. Using NumberFormat.format()

4.使用NumberFormat.format()

The NumberFormat class also provides a format method similar to the String class, but NumberFormat is faster and with it, we can specify the rounding mode to achieve either truncation or rounding.

NumberFormat 类也提供了与String类类似的format方法,但NumberFormat更快,而且通过它,我们可以指定舍入模式,以实现截断或舍入。

The setMaximumFractionDigits() method tells the formatter how many fractional digits after the decimal point to include in the output:

setMaximumFractionDigits()方法告诉格式化器在输出中包括多少个小数点后的小数点。

NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(0);
String rounded = nf.format(doubleValue);

Curiously, NumberFormat doesn’t use HALF_UP by default. Instead, it uses HALF_EVEN rounding by default, meaning it will round like normal except at .5, in which case it will pick the nearest even number.

奇怪的是,NumberFormat默认不使用HALF_UP相反,它默认使用HALF_EVEN四舍五入,这意味着它将像普通四舍五入一样,除了0.5,在这种情况下,它将选择最近的偶数

While HALF_EVEN is helpful with statistical analysis, let’s use HALF_UP to be consistent:

虽然HALF_EVEN对统计分析有帮助,但我们还是用HALF_UP来表示一致。

nf.setRoundingMode(RoundingMode.HALF_UP);
String rounded = nf.format(doubleValue);

And, we can change this and achieve truncation by setting the formatter to use the FLOOR rounding mode instead:

而且,我们可以通过将格式化器设置为使用FLOOR 四舍五入模式来改变这一点并实现截断:

nf.setRoundingMode(RoundingMode.FLOOR);
String truncated = nf.format(doubleValue)

And now, it will truncate instead of round.

而现在,它将截断,而不是取整。

5. Using DecimalFormat.format()

5.使用DecimalFormat.format()

Similar to NumberFormat, the DecimalFormat class can be used to format double values. However, instead of setting the output format with method calls, we can tell the formatter what output we want by providing the constructor with a specific pattern:

NumberFormat类似,DecimalFormat类可用于格式化double值。然而,我们不需要通过方法调用来设置输出格式,我们可以通过向构造函数提供特定的模式来告诉格式器我们想要什么输出:

DecimalFormat df = new DecimalFormat("#,###");
df.setRoundingMode(RoundingMode.HALF_UP);
String rounded = df.format(doubleValue);

The “#,###” pattern signifies that we want the formatter to only return the integer part of the input. It also signals that we want the digits grouped in threes separated by a comma.

“#,##”模式表示我们希望格式化器只返回输入的整数部分。它还表明我们希望数字以逗号分隔成三组。

The same rounding defaults apply here so if we want to output a truncated value we can set the rounding mode to FLOOR:

同样的四舍五入默认值也适用于此,所以如果我们想输出一个截断的值,可以将四舍五入模式设置为FLOOR

df.setRoundingMode(RoundingMode.FLOOR);
String truncated = df.format(doubleValue)

6. Using BigDecimal.toString()

6.使用BigDecimal.toString()

The last approach we’ll look at is BigDecimal, which we’ll include because it out-performs NumberFormat and DecimalFormat for larger doubles.

我们要看的最后一个方法是BigDecimal,我们要把它包括在内,因为对于较大的doubles,它比NumberFormatDecimalFormat表现得更好。

We can use BigDecimal‘s setScale method to tell whether we want to round or truncate:

我们可以使用BigDecimalsetScale方法来告诉我们是要四舍五入还是截断。

double largeDouble = 345_345_345_345.56;
BigDecimal big = new BigDecimal(largeDouble);
big = big.setScale(0, RoundingMode.HALF_UP);

Remember that BigDecimals are immutable so, like Strings, we need to reset the value.

请记住,BigDecimals是不可变的,所以,像字符串一样,我们需要重置值。

And, then, we just call BigDecimal‘s toString:

然后,我们只是调用BigDecimaltoString

String rounded = big.toString();

7. Conclusion

7.结论

In this tutorial, we looked at the different ways in which we can convert a double to a String while removing decimal places. We provided approaches that would output either rounded or truncated values.

在本教程中,我们研究了将double转换为String的不同方法,同时删除了小数位。我们提供了将输出四舍五入或截断的值的方法。

As usual, the samples and benchmarks are available over on GitHub.

像往常一样,样本和基准可在GitHub上获得