Click to See Complete Forum and Search --> : Fixed point number to and from string


SBeier
November 27th, 2010, 09:03 AM
Hi, I am trying to make a fixed point number in c#.
I would like to be able to convert it to a decimal string, and to parse a decimal string into a fixed point number. I can't find a good way of doing it though. The bits before the comma is ofcourse not a problem, but how would you convert the part of the number after the comma?

btw, I have 19 bits before the comma, and 12 bits after the comma.

answer
December 9th, 2010, 10:13 AM
int D = before comma
int d = after comma

once parsed your fixed point becomes (D << 12) + d.
Now to parse d (assuming base 10 for string) you go through every digit and multiply by 10^(-digit)

example: x=12.1234
lets take 1234 now lets construct d
the decimal part of x can be represented as
1/10 + 2/100 + 3/1000 + 4/10000
The numerator can be represented as fixed point.
d = (1 << 12)/10 + (2 << 12)/100 + (3 << 12)/1000 + (4 << 12)/10000

it works by first converting the digit to fixed point representation (shifting by 12 so its 1.00 or 2.00 etc ...) then dividing by 10, 100, 1000 etc ... to.

Since you have only 12bits the fourth digit will have a poor precision.