简体   繁体   中英

BigDecimal Java. How to append zeros in front

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!

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

String.format("%010d", BigInteger.valueOf(2353))

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

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.

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

If the maximum number of digits is 10 and only whole numbers are allowed you don't need anything more than to use long with standard formatting:

long myNumber = 123456;
System.out.printf("%010d%n", myNumber);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM