I am helping a friend with a small electronics project using a PIC microcontroller 16F877 (A) which I am programming with mikroC.
I have run into a problem which is that I have a floating point number in a variable lets say for example 1234.123456 and need to split it out into variables holding each individual number so I get Char1 = 1, Char2=2 etc etc. for display on LCD. The number will always be rounded to 3 or 4 decimal places so there should be a need to track the location of the decimal point.
Any advice on how to get this split would be greatly appreciated.
Answer
There's numerous ways of doing it. You may find your compiler has a library function to do it for you. It may be possible with:
- sprintf() / snprintf()
- dtostrf()
- dtoa()
Alternatively, it's not too hard to write your own routine to do it. It's just a case of first working out how many digits before the decimal point there are, dividing it by 10 that many times, then taking the integer portion repeatedly while multiplying by 10, making sure you add the decimal point in at the right place.
So in pseudo-code it may look something like:
If the value < 0.0:
Insert - into string
Subtract value from 0.0 to make it positive.
While the value <= 10.0:
Divide by 10
Increment decimal counter
For each digit of required precision:
Take the integer portion of the value and place it in the string
Subtract the integer portion from the value
Decrement decimal counter
If decimal counter is 0:
Insert decimal point
Multiply the value by 10.
No comments:
Post a Comment