View previous topic :: View next topic |
Author |
Message |
jojos
Joined: 30 Apr 2007 Posts: 64
|
Obtain the decimal part of a number |
Posted: Fri Jul 04, 2008 12:25 am |
|
|
Hello.I want to convert the a float to decimal.To be more accurate i will use an example:
I have this operation: 9.65*4.5 The result of this operation is 43.425. I want to get apart from the integer part of the number the decimal part of the result (425) ,so i can show it in the lcd.
When i use this code i get these results on the watch window of MpLab:
Code: |
#include "18F2520.h"
#include <string.h>
#fuses XT,NOWDT,NOPROTECT,NOLVP,PUT,NOPBADEN,NOBROWNOUT//BROWNOUT_SW,BORV27//,BORV27 //INTERNAL OSCILLATOR NO CLOCK
#use delay(clock=3276800) //3276800
void main(void)
{
float32 d=0;
int16 x=0;
d=9.65*4.5; // d=867380612
x=d; // x=43
} |
So where is the decimal part of the number?
Thank you in advance and sorry if this is a silly question |
|
|
herselmann
Joined: 31 May 2008 Posts: 7
|
|
Posted: Fri Jul 04, 2008 12:41 am |
|
|
Maybe you should consider getting your OWN signiture string! _________________ There are only 10 kinds of people, those who understand binary and those who don't. |
|
|
jojos
Joined: 30 Apr 2007 Posts: 64
|
|
Posted: Fri Jul 04, 2008 1:02 am |
|
|
Thanks for your <<help>> herselmann |
|
|
herselmann
Joined: 31 May 2008 Posts: 7
|
|
|
languer
Joined: 09 Jan 2004 Posts: 144 Location: USA
|
|
Posted: Fri Jul 04, 2008 4:28 pm |
|
|
I would always recommend avoiding floats unless you absolutely have to. They take much more space and their operations are slower.
Look at using the int32 to fit your math results and the modulus operator (%) to access the remainder of a division. In your case you would have:
Code: | int32 ans
int16 ans_int ans_fract
ans = (965 * 45) -> fractional numbers scaled-up to use integer math
ans_int = ans / 1000 -> integral part of 9.65*4.5
ans_fract = ans % 1000 -> fractional part of 9.65*4.5 (it only works-out this nice when power-of-10 are used as the scaling factor) |
Looking at the CCS manual there is already a function, modf, that does this for floats. |
|
|
|