java 如何删除字符串值中的尾随零并删除小数点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25541684/
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-11-02 08:11:43  来源:igfitidea点击:

How to remove trailing zero in a String value and remove decimal point

javastringintdouble

提问by Marjer

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

This removes trailing zeros in (10.10 and 10.2270), but I do not get my expected result for 1st and 2nd inputs.

这会删除 (10.10 和 10.2270) 中的尾随零,但我没有得到第一个和第二个输入的预期结果。

Input

输入

10.0
10.00
10.10
10.2270

Expected output

预期输出

10
10
10.1
10.227

回答by jdphenix

The Java library has a built-inclass that can do this for it. It's BigDecimal.

Java 库有一个内置类可以为它做这件事。它是BigDecimal

Here is an example usage:

这是一个示例用法:

BigDecimal number = new BigDecimal("10.2270");  
System.out.println(number.stripTrailingZeros().toPlainString());

Output:

输出:

10.227

Note: It is important to use the BigDecimalconstructor that takes a String. You probably don't want the one that takes a double.

注意:使用BigDecimal带有String. 你可能不想要一个需要double.



Here's a method that will take a Collection<String>and return another Collection<String>of numbers with trailing zeros removed, gift wrapped.

这是一个方法,它将接受一个Collection<String>并返回另一个Collection<String>删除尾随零的数字,礼品包装。

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

Example usage:

用法示例:

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

Outputs:

输出:

[10, 10, 10.1, 10.227]

回答by Viraj

Try

尝试

DecimalFormat decimalFormat = new DecimalFormat("#.##");
String string1 = decimalFormat.format(10.000);

回答by TheLostMind

Try regex like this :

像这样尝试正则表达式:

public static void main(String[] args) {
    String s = "10.0";
    System.out.println(s.replaceAll("[0]+$", "").replaceAll("(\.)(?!.*?[1-9]+)", ""));

}

O/P:
10

input :String s = "10.0750";
O/P : 10.075

input : String s = "10.2750";
O/P : 10.275