如何删除字符串值中的尾随零并删除小数点 [英] How to remove trailing zero in a String value and remove decimal point
问题描述
如何删除字符串值中的尾随零,如果字符串仅包含小数点后的零,则删除小数点?
我使用以下代码:
How do I remove trailing zeros in a String value and remove decimal point if the string contains only zeros after the decimal point? I'm using the below code:
String string1 = Double.valueOf(a).toString()
这将删除(10.10和10.2270)中的尾随零,但是我没有得到我的预期结果,第二输入。
This removes trailing zeros in (10.10 and 10.2270), but I do not get my expected result for 1st and 2nd inputs.
输入
10.0
10.00
10.10
10.2270
预期输出
10
10
10.1
10.227
推荐答案
Java库有一个内置类,可以做到这一点。它是 BigDecimal
。
The Java library has a built-in class that can do this for it. It's BigDecimal
.
以下是一个示例用法:
BigDecimal number = new BigDecimal("10.2270");
System.out.println(number.stripTrailingZeros().toPlainString());
输出:
10.227
注意:使用 BigDecimal
构造函数,它需要一个 String
。你可能不想要一个 double
。
Note: It is important to use the BigDecimal
constructor that takes a String
. You probably don't want the one that takes a double
.
这是一个方法,将采用 Collection< String>
并返回另一个 Collection< String>
的数字,尾随零被删除,礼物包装。
Here's a method that will take a Collection<String>
and return another Collection<String>
of numbers with trailing zeros removed, gift wrapped.
public static Collection<String> stripZeros(Collection<String> numbers) {
if (numbers == null) {
throw new NullPointerException("numbers is null");
}
ArrayList<String> value = new ArrayList<>();
for (String number : numbers) {
value.add(new BigDecimal(number).stripTrailingZeros().toPlainString());
}
return Collections.unmodifiableList(value);
}
使用示例:
ArrayList<String> input = new ArrayList<String>() {{
add("10.0"); add("10.00"); add("10.10"); add("10.2270");
}};
Collection<String> output = stripZeros(input);
System.out.println(output);
输出:
[10, 10, 10.1, 10.227]
这篇关于如何删除字符串值中的尾随零并删除小数点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!