Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在其他字符串编号之前剪切所有字符串“0”_Java - Fatal编程技术网

Java 如何在其他字符串编号之前剪切所有字符串“0”

Java 如何在其他字符串编号之前剪切所有字符串“0”,java,Java,我的经纪人提供的价格编号数据如下: String Price = "00000001970.00"; String Price1 = "0000000295.00"; 这是我尝试使用的代码: String Price2 = price.replace ("0", ""); 但结果是价格2=197。我的期望是价格2=1970 有人能告诉我如何解决这个问题吗?String price=00000001970.00;

我的经纪人提供的价格编号数据如下:

String Price = "00000001970.00";
String Price1 = "0000000295.00";
这是我尝试使用的代码:

String Price2 = price.replace ("0", "");
但结果是价格2=197。我的期望是价格2=1970

有人能告诉我如何解决这个问题吗?

String price=00000001970.00; //如果你不在乎小数点 System.out.printlprice.split\\\[0]。replaceFirst ^0+?!$; //如果您确实关心小数点: System.out.printlnprice.replaceFirst ^0+?!$;
请参见

您需要使用如下正则表达式:

yourstring.replaceFirst("^0+(?!$)", "");

伙计。有一大堆解决你问题的办法。例如,您可以如下所示进行查找: `字符串价格=00000001970.00

    Double dv = Double.valueOf(price);

    System.out.println(dv);

    int intValue = dv.intValue();

    System.out.println(intValue);
 String substring = price.substring(0,price.indexOf("."));

 System.out.println(Integer.valueOf(substring));
` 您将得到如下结果:

` 1970.0

1970年`

此外,您还可以按如下方式查找:

`字符串价格=00000001970.00

    Double dv = Double.valueOf(price);

    System.out.println(dv);

    int intValue = dv.intValue();

    System.out.println(intValue);
 String substring = price.substring(0,price.indexOf("."));

 System.out.println(Integer.valueOf(substring));

`

我个人不太喜欢正则表达式,所以我尽量避免使用正则表达式

假设所有字符串都是数字,您可以将它们解析为BigDecimal,然后根据需要打印。如果您关心精度,则BigDecimal优于Double

要实现你想要的,你可以这样做:

public static void main(String args[]) {
    String price = "00000001970.00";
    String price1 = "0000000295.0011";
    BigDecimal num = new BigDecimal(price);
    BigDecimal num1 = new BigDecimal(price1);
    DecimalFormat df = new DecimalFormat("#.###");
    System.out.println(df.format(num));
    System.out.println(df.format(num1));
}
这些数字的格式如下:

1970
295.001

要了解有关可能格式的更多信息,请阅读。

最简单的方法似乎是使用org.apache.commons.lang3.RegExUtils类中的replaceFirst方法:

String price = RegExUtils.replaceFirst("00000001970.00", "0+(\\d)", "$1");
这将用该数字替换前零后任何数字的子字符串

输出:


这回答了你的问题吗?这回答了你的问题吗?Double和int不是处理金额的合适数据类型。这两种情况都可能导致损失价值的一部分。建议将此作为价格编号