Search code examples
javabigdecimal

unexpected output in big decimal class, java


import java.math.BigDecimal;
import java.util.Scanner;

public class bigd {

    public static void main(String[]args) {

        Scanner s=new Scanner(System.in);   
        int count=s.nextInt();

        // take  n inputs and put them in array
        String [] number=new String [count] ;

        for(int i=0; i<number.length; i++) {        
            number[i]=s.next();     
        }// end transfer forr 

        BigDecimal [] big=new BigDecimal[count];

        for(int i=0;i<number.length; i++) { 
            big[i]= new BigDecimal(number[i]);  
        }// big loop

        //sorting 
        for(int i=0; i<big.length; i++) {   
            for(int j=i+1; j<big.length; j++) { 
                if(big[i].compareTo(big[j])<0) {
                    BigDecimal temp=big[i];
                    big[i]=big[j];
                    big[j]=temp;        
                }// if end      
            }// inner loop  
        } // outer sort loop 
        //end soting

        //display
        for(int i=0; i<big.length;i++) {
            System.out.println(" "+ big[i]);
        }//end disp

        s.close();  
    }// main

}// class

Problem here is when I sort the provided input it adds a zero in front of numbers like .12, so it will output the number with the said 0 like 0.12.

How to output the same number .12?

I need to know why a zero is being added.


Solution

  • System.out.println(" "+ big[i]) calls the toString() method of BigDecimal, and that's how it's implemented, which makes sense, since that's normally how numbers are written.

    You could add string manipulation to the result of toString(), but I am not sure why you want to.

    What is your motivation for not having the zero there?