Why they are needed: As you may know, using floats is a very bad idea (in all languages) when dealing with money.
Careful: Not thoroughly tested. Comments and bug reports welcome
EDIT1: code updated with Stargate's bugfix
Code: Select all
Procedure.q MoneyStringToCents(amount.s, howmanydecimals=2)
WholePart.s = StringField(amount, 1, ".")
DecimalsPart.s = StringField(amount, 2, ".")
DecimalsPart = LSet(DecimalsPart, howmanydecimals, "0")
ProcedureReturn Val(WholePart + DecimalsPart)
EndProcedure
;Debug ValF("3.00028224")
Debug MoneyStringToCents("3.00028224")
Debug MoneyStringToCents("324")
Debug MoneyStringToCents("1000000000000002")
Debug "---"
Procedure.s CentsToMoneyString(amount.q, howmanydecimals=2)
DecimalsPart.s = Right(Str(amount), howmanydecimals)
If Len(DecimalsPart) < howmanydecimals : DecimalsPart = RSet(DecimalsPart, howmanydecimals, "0") : EndIf
WholePart.s = "0" : If Len(Str(amount)) > howmanydecimals : WholePart.s = Left(Str(amount), Len(Str(amount)) - howmanydecimals) : EndIf
result.s = WholePart + "." + DecimalsPart
ProcedureReturn result.s
EndProcedure
Debug centsToMoneyString(2245124)
Debug centsToMoneyString(38224)
Debug centsToMoneyString(5)
Debug centsToMoneyString(400) ;; €4.00