Android Question Rounding BigDecimals [Solved]

Roger Daley

Well-Known Member
Licensed User
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.


Thanks in advance

Roger
 

Roger Daley

Well-Known Member
Licensed User
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
 
Upvote 0

Roger Daley

Well-Known Member
Licensed User
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
 
Upvote 0

Roger Daley

Well-Known Member
Licensed User
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
 
Upvote 0
Top