Remove the leading 0's till the decimal

一曲冷凌霜 提交于 2019-12-01 13:10:57

问题


I want to remove the leading zeros in the decimal numbers.

So i want the output should be .324 not 0.324. I tried str.replaceFirst("^0+(?!$)", ""); Didn't work and i also tried the regex! No results! And yes I am working with BigDecimal.


回答1:


Try this

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



回答2:


if you are trying to format BigDecimal having value 0.324 to .324. Then below works

    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



回答3:


do you want this for printing purposes? you wont be able to do any math using this, so i guess yes. then you could do:

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

output

.254000000000000003552713678800500929355621337890625



来源:https://stackoverflow.com/questions/30959109/remove-the-leading-0s-till-the-decimal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!