Home > Software design >  BigDecimal Java. How to append zeros in front
BigDecimal Java. How to append zeros in front

Time:11-19

My question is basically the following:

When I use a value with BigDecimal, how do I append zeros in front of a random number? Say I want to have a number <10 following an entirely random pattern. Now i want to add zeros in front of the number, so the actual amount adds up to 10 numbers.

Here's an example: BigDecimal num = new BigDecimal(2353);

Now I want to have that ouput: 0000002353

Is there a function that appends numbers to a BigDecimal type? I couldn't find any.

I tried using a while loop that checks whether the number is less than ten. But I don't understand the Big Decimal well enough to actually compare integral values to the BigDecimal types. Thanks for any help in advance!

CodePudding user response:

BigDecimal is meant to be used for storing large floating point numbers. Since in a floating-point number there isn't any difference between 0000002353 and 2353, there is no reasonable way to append leading 0's to a BigDecimal just as there is no reasonable way to append leading 0's to a normal float. According to the behavior you're looking for, I would suggest using a String to store your number, and then convert to and from BigDecimal when you want to perform any operations.

To compare an integral type to a BigDecimal, first convert the variable to a BigDecimal and then call BigDecimal's compareTo method. More info is in this question.

CodePudding user response:

If you use a BigInteger instead (or any integer type, such as int or long) you can format the value with

String.format("0d", BigInteger.valueOf(2353))

The leading 0 in the format strings means pad with 0, the following 10 is the desired length...

CodePudding user response:

Since you're interested in formatting the number, you might want to look at DecimalFormat class, which allows to format floating point and integer numbers according to the specified pattern.

BigDecimal num = new BigDecimal(2353);
        
DecimalFormat f1 = new DecimalFormat("0000000000");
DecimalFormat f2 = new DecimalFormat("0,000,000,000");
        
System.out.println(f1.format(num));
System.out.println(f2.format(num));

Output:

0000002353
0,000,002,353
  • Related