4

I am trying to figure out how to store 1/3, or any fraction which results in an infinitely repeating decimal value in MySQL. I cannot just use 3.333333 because it obviously does not total to 100. I have been reading about the float datatype but i'm not sure if this will work. Any help would be appreciated.

Thank you

Progger
  • 2,266
  • 4
  • 27
  • 51
  • 1
    I don't think there is a default way to store a fraction like this - other than in plain text of course. Any floating point integer is never going to truly add up to 100, no matter how long it is, however you could always just round to the closest full number with your code once you have pulled it out. It all depends though in what your doing with these fractions though really. – BenOfTheNorth Feb 21 '12 at 21:34
  • This may be a silly question, but what are you trying to achieve? I mean to what is storing a precise fraction required for – Simon at The Access Group Feb 21 '12 at 22:42
  • I am writing an app that calculates ownership of assets. If the asset is being shared by 3 people, for example, I want to provide the option for diving by percentage (20%, 20%, 60%) or by fraction (1/3, 1/3, 1/3). My table only accepts decimals so if I want to equally divide an asset by 3, or 6, or anything that isn't representable by a decimal, I don't know how to record it. – Progger Feb 22 '12 at 04:29

2 Answers2

10

You could potentially represent all rational numbers (including integers) as "numerator" and "denominator". So in your table you'd have a numerator and denominator columns, and your app would have logic to store numbers using that form.

You would still be unable to store irrational numbers precisely with this technique (i.e. if you want to store Pi, you'd need a fractional approximation anyway).

See here for what rational numbers are, so you can understand the limitations of this technique.

http://en.wikipedia.org/wiki/Rational_number

Roadmaster
  • 5,297
  • 1
  • 23
  • 21
  • Awesome, 104348/33215 see here for more approximations and how to calculate them. http://mathworld.wolfram.com/PiApproximations.html – Roadmaster Feb 21 '12 at 21:49
7

Store the numerator and the denominator in separate columns. It's really that simple. The real problem comes later when you want to add up all the fractions. Some languages have built-in facilities to do so, but I don't think MySQL does.

John Pick
  • 5,562
  • 31
  • 31