Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I safely perform money related calculations in PHP?

Tags:

php

finance

I'm working on a few report output scripts that need to do some rudimentary calculations on some money values.

I am aware of the limitations of floating point arithmetic for this purpose, however the input values are all in a decimal format, so if I use the arithmetic operators on them PHP will cast them to floats.

So what is the best way to handle the numbers? Should I use BCMath? Is there something akin to Decimal in .NET? Or is it safe to use the arithmetic operators if I cast back to int?

like image 352
Shabbyrobe Avatar asked May 23 '09 02:05

Shabbyrobe


2 Answers

If you use BCMath all values will be stored in strings and passed to the functions as strings, just as the result will be a string. So, you needn't do any casting but ensure that the number given to the function is a value numeric value. Personally, if the math requires a high amount of precision on the decimal side then use BCMath.

like image 77
Robert K Avatar answered Nov 05 '22 18:11

Robert K


Don't work in Dollars ($1.54), work in cents: (154c). Unless you need to be performing tasks where fractions of a cent are important, then you'll be working with integers and all is well. If you are interested in tenths of a cent, then just multiply everything by ten!

like image 13
nickf Avatar answered Nov 05 '22 17:11

nickf