删除前导 0 直到小数点

Remove the leading 0's till the decimal

我想删除小数中的前导零。

所以我希望输出应该是 .324 不是 0.324。 我试过 str.replaceFirst("^0+(?!$)", ""); 没用,我也试过正则表达式! 没有结果! 是的,我正在使用 BigDecimal。

试试这个

str = str.replaceFirst("^0\.", ".");

你想要这个用于打印目的吗?您将无法使用它进行任何数学运算,所以我想是的。那么你可以这样做:

BigDecimal number =new BigDecimal(0.254); 
       System.out.println(number.toString().substring(number.toString().indexOf("0.")+1));

输出

.254000000000000003552713678800500929355621337890625

如果您尝试将值 0.324BigDecimal 格式化为 .324。然后下面的作品

    BigDecimal bd=new BigDecimal("0.23");// this will replace with your BigDecimal
    DecimalFormat df=null;
    //check if number is a fraction
    if(bd.remainder(BigDecimal.TEN).compareTo(BigDecimal.ZERO)>0)
      df=new DecimalFormat(".###");
    else
      df=new DecimalFormat("##");

    System.out.print(df.format(bd));// .format returns string as .23

0.23->.23
0->0
90->90
80.12->80.12