Issue
My input field BigDecimal
num may contain both integer and floating numbers.
num = 45
or
num = 45.5343434
If the BigDecimal
input field num
contains decimal places, then I would like to limit the decimal places to 4.
Desired Output : 45.5343 if input num = 45.5343434
Desired Output : 45 if input num=45
How can I do that?
Solution
You are interested in what is called the scale of your BigDecimal
.
Call BigDecimal#scale
.
BigDecimal x = new BigDecimal( "45.5343434" );
BigDecimal y = new BigDecimal( "45" );
x.scale(): 7
y.scale(): 0
You asked:
I would like to limit the decimal places by 4
Test for the scale being larger than four. If so, round.
BigDecimal num = new BigDecimal(45);
if (num.scale() > 4) {
num = num.setScale(4, RoundingMode.HALF_UP);
}
System.out.println(num);
Output:
45
In case of more decimals:
BigDecimal num = new BigDecimal("45.5343434");
45.5343
You can choose a different rounding mode to fit with your requirements.
Answered By - Ole V.V. Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.