B4J Question Using Decimal Number

aaronk

Well-Known Member
Licensed User
Longtime User
Hi,

I am viewing an Excel sheet in my B4J app, and a column contains a price as a decimal number.

B4X:
Type Sales(invoice As String, Account As String, customer As String, Amount As String, CostCode As Int, Date As String)

XL.Initialize
    Dim result As XLReaderResult = XL.Reader.ReadSheetByName(File.DirApp, "sales.xlsx", "Invoices")
   
    For Row1Based = 2 To result.BottomRight.Row0Based + 1
       
        Dim s As Sales
        s.invoice = result.Get(XL.AddressOne("A", Row1Based))
        s.Account = result.Get(XL.AddressOne("B", Row1Based))
        s.customer = result.Get(XL.AddressOne("C", Row1Based))
        s.Amount = result.Get(XL.AddressOne("F", Row1Based))
        s.CostCode = result.Get(XL.AddressOne("M", Row1Based))
        s.Date = result.Get(XL.AddressOne("O", Row1Based))
        SalesMap.Put(s.invoice,s)
           
    Next

The above works, and it will store the values in the map.

However, I am trying to work out how to add numbers together (the Amount value).

I am storing it as a 'String' as I am not sure what I need to use? If I store it as 'Int' then the decimal number will drop.

Anyone know the correct way in storing the 'Amount' value so I can add a value to it later on ?
 

DonManfred

Expert
Licensed User
Longtime User
I suggest Double
 
Upvote 0

Brian Dean

Well-Known Member
Licensed User
Longtime User
If you expect to add together or multiply monetary amounts then the correct practice is to store those amounts in the smallest unit of currency - that would be pence in the UK, cents in the US and similarly in other countries - as integers. If you store monetary amounts as floating point values then there will often be a degree of approximation (in decimal parts of a dollar, for instance) and possible an error when multiplying and rounding to, usually, two decimal places.

If you are dealing with only one or two items at a time then you might get away with it; that does not make it good practice.
 
Upvote 0

agraham

Expert
Licensed User
Longtime User
If you need decimal accuracy then my BigNumbers library will work under B4J.
 
Upvote 0
Top