# Android QuestionRounding BigDecimals [Solved]

#### Roger Daley

##### Well-Known Member
Longtime User
Hi All

A BigNumbers question. Can someone please clarify how I should round a BigDecimal to its integer value.

IE: For a Double, I would use Double1 = NumberFormat(Double1,1,0)

For a BigDecimal would I use "BigDecimal1.Round (precision As Int, 0)"?
If so, what goes in the "precision As Int" part. I have researched precision but it appears to assume that I already know the answer.

Roger

#### Erel

##### B4X founder
Staff member
Longtime User
You can use NumberFormat(BigDecimal.DoubleValue, 1, 1)

#### Roger Daley

##### Well-Known Member
Longtime User
Sorry Erel,

This negates the advantage of using the BigNumber library by returning the number to the precision of a Double. I have tried this and it introduces the errors I was trying to avoid.

The question remains, how do I use the BigDecimal.Round to correctly round a BigDecimal back to it's integer?

Regards Roger

#### Erel

##### B4X founder
Staff member
Longtime User
Can you give an example of the stored number and the desired rounded number?

#### Roger Daley

##### Well-Known Member
Longtime User
Examples: Not real code but just as demo.

BigDecimal1.Initialize(16): BigDecimal1.Pow(16) [IE 16 digits of hex]
'BigDecimal1 = 18446744073709551616

If BigDecimal1 equaled 18446744073709551615.999 it would need to round up to 18446744073709551616 [Not a real situation, just a demo of principle.]
If BigDecimal1 equaled 18446744073709551616.123 it would need to round down to 18446744073709551616
I can't get BigDecimal1.Round to do this. I have tried BigDecimal1.Divide2(1, BigDecimal1.Precision, 0) and other work-arounds but no joy.

Numberformat does this very well for Doubles but unfortunately:
Double1 = Power(16,16)
'Double1 = 1.8446744073709552E19 significantlly inaccurate for 16 digit hex using AND, OR, XOR Etc.

I hope this makes sense.

Roger

#### Erel

##### B4X founder
Staff member
Longtime User
You need to use SetScale:
B4X:
``````Dim bd As BigDecimal
bd.Initialize("18446744073709551615.999")
bd.SetScale2(0, bd.ROUND_HALF_UP)
Log(bd.ToPlainString)``````

#### Roger Daley

##### Well-Known Member
Longtime User
Thanks Erel,

Your example opened the way for me. My solution is:

B4X:
``````Private BigDecimal1  As BigDecimal       BigDecimal1.Initialize("18446744073709551615.999")
BigDecimal1 =  RoundBD(BigDecimal1,0)
Log("BigDecimal1        "&BigDecimal1)

'Sub takes BigDecimal [BD ] to be rounded and the number of Decimal Places [DP]
Sub RoundBD(BD As BigDecimal,DP As Int) As BigDecimal
BD.Round(BD.Precision - BD.Scale + DP, BD.ROUND_HALF_UP )
Return BD
End Sub``````

It all appears work as expected.

Regards Roger

Replies
1
Views
1K
Android Code Snippet logarithms using BigDecimals
Replies
0
Views
2K
Replies
1
Views
2K
Android Question BigDecimal problem
Replies
3
Views
2K
B4A Library BigNumbers library
Replies
20
Views
15K