0

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.

Vishal
  • 391
  • 5
  • 20

3 Answers3

4

Try this

str = str.replaceFirst("^0\\.", ".");
Raman Shrivastava
  • 2,923
  • 15
  • 26
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
Amit.rk3
  • 2,417
  • 2
  • 10
  • 16
  • 1
    It then adds .0 to non-decimals! for e.g, 90 becomes 90.0 and 0 becomes .0 @Amit.rk3 – Vishal Jun 20 '15 at 21:50
  • @VishalSaini You can't have different formatting for same variable based on it's value. That is something which you have to handle in code, which is pretty easy. If I understand your requirement, you need this format only for decimals between 0 to 1. You can add simple if condition in your code to check if your value is lesser than one by `value.compareTo(BigDecimal.ONE)` . Then you can use above format, else use whatever is your existing format for other numbers greater than or equal to 1. – Amit.rk3 Jun 20 '15 at 22:00
  • Actually Sir! The numbers are greater than one! for e.g, 96.6 324.44 So i have to sort these numbers and then print in the sorted way! With decimals as .45 or .### – Vishal Jun 20 '15 at 22:05
0

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

Skaros Ilias
  • 1,008
  • 12
  • 40