3

How I can store the BigDecimal() same as input?

I need to store real numbers using BigDecimal() which may contain following:

02.34
0.12
.12
0
000.000

I used the following approach :

Scanner sc= new Scanner(System.in);
int n=sc.nextInt();
BigDecimal[] amount = new BigDecimal[n];

for(int i=0;i<n;i++) {
    amount[i]=sc.nextBigDecimal();
}

But while printing, it prints formatted. Like this:

2.34
0.12
0.12
0.000
0

I want it should be same as inputted. Therefore please let me know that how could I manage to store inputs intact.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Rohit Nigam
  • 708
  • 8
  • 23

4 Answers4

5

the following code should solve your problem, Keep your string as is and convert it into BigDecimal only when you are comparing

 Arrays.sort(s, Collections.reverseOrder(new Comparator<String>() {
        @Override
        public int compare(String a1, String a2) { 
           BigDecimal a = new BigDecimal(a1);
            BigDecimal b = new BigDecimal(a2);
            return a.compareTo(b);

        }
    }));
Suresh
  • 38,717
  • 16
  • 62
  • 66
1

Since input is originally a string, the only way to store it intact is to store it as a String.

If you later need to do some math on the numbers, convert them then. You could also possibly store them as both String and BigDecimal in an object.

Roger Gustavsson
  • 1,689
  • 10
  • 20
1

If you want to store input intact, store it as a String. This is exactly the built-in type dedicated to storing character sequences exactly as entered.

BigDecimal, on the other hand, has a numeric representation with no mechanism for storing its decimal input. In fact, you can initialize BigDecimal without providing a decimal representation at all - e.g. through a sequence of arithmetical operations, in which case the initial representation would not be applicable at all.

If you need to do this in many places, make a class for it. Store the original string, along wit BigDecimal that it represents. This way you would be able to do the conversion only once, and keep the original representation along with it:

class OrigBigDecimal {
    private String orig;
    private BigDecimal val;
    public OrigBigDecimal(String s) {
        orig = s;
        val = new BigDecimal(s);
    }
    public String toString() { return s; }
    public BigDecimal getVal() { return val; }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

There are a number of ways to approach this:

1- You can create a small elegant object that has 2 variables, a BigDecimal and a string, and its constructor takes the input as a string, store it in a string and parse it and store it in the BigDecimal.

2- You can configure the BigDecimal output format per input:

Format of BigDecimal number

Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

Community
  • 1
  • 1
Mr. M
  • 62
  • 1
  • 15