SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Enthusiast
    Join Date
    Jan 2006
    0 Post(s)
    0 Thread(s)

    Fractions in MySQL (and PHP)


    I'm wondering if we can do math fraction operations and also store in columns, by keeping it always in fractions format (dividend/divisor) including if there's an integer before the fraction like 5¼.

    I did some readings and I only found workarounds. I'm not doing the workarounds yet because a scientific calculator can do what I want (except for the "storing" part) so I assume there's a "easy way" to achieve this in MySQL also.

    In scientific calculators it's something like:

    5¬3¬4 + 2¬3¬4 = 8¬1¬2

    Can't we do the above with MySQL? While also storing the result in fraction format?


    I really need to add/subtract a column with fraction numbers, and it has to be fraction to keep it precise.

    Like if I UPDATE table SET col = col+3¬1¬3 three times, the column value have to be 10 exactly.

    Thank you


    Right now, I've decided to use 2 INT columns to store the dividend and divisor, and do the corresponding process' to get as close as I wanted above. Still many flaws, for example, cannot store 5¼ but it needs to be 21 & 4.

    Do you think it's the best I can do?

  2. #2
    ✯✯✯ silver trophybronze trophy php_daemon's Avatar
    Join Date
    Mar 2006
    2 Post(s)
    0 Thread(s)
    Here's what I'd do. Create a class to save fractions:

    Code php:
    class Fraction{
      public $integer;
      public $dividend;
      public $divisor;
      function __construct($integer,$dividend,$divisor){
    $fraction=new Fraction(5,1,4);

    Not the best OOP, but as an example. Then serialize it and store it in db.

    Of course any calculations can only be done in php after unserializing the object. Any sorting is hardly possible as well. It's a php side solution, so having also operator classes, you can easily build a mechanism for calculations.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts