Hi,
I have an issue to convert a float to a string with the Coldfire MCF52259. Here what I am trying to do:
char str[10];
float fval = 1201 / 10;
sprintf (str, "%3.1f\n", fval);
The debugger shows that fval is 120.100. This is what I expect to see. But "str" is not set correctly. If I do the same thing with an integer, there is no problem:
char str[10];
int val = 1201
sprintf (str, "%d\n", val);
What I am doing wrong?
Thanks in advance
This thread may give you a hint for a solution:
icarus31 wrote:
float fval = 1201 / 10;
...
The debugger shows that fval is 120.100.
That's odd. This code should initialize fval with 120.0. I wonder if you edited the code before posting it. Maybe there are other significant differences?
icarus31 wrote:
sprintf (str, "%3.1f\n", fval);
Perhaps you meant "%5.1f"? Or simply "%.1f"?
icarus31 wrote:
But "str" is not set correctly.
What's the contents of str?
SciFi,
I should say "float fval = (float) 1201/10;" I did not copy paste the code because I was working on another computer.
The "%3.1f" was basically make sure it will be 3 digits before the dot and 1 digit after it. So, it should print 120.1. The "%5.1f" or "%.1f", for that particular case will have the same result as what I wrote.
The "str" variable was set to :
str[0] = 'f'
str[0] = '\x00'
str[1] = '\x91'
str[2] = '\x9C'
str[3] = '\x00'
str[4] = '\x00'
str[5] = '\x00'
str[6] = '\x00'
str[7] = '\x00'
str[8] = '\x00'
icarus31 wrote:The "%3.1f" was basically make sure it will be 3 digits before the dot and 1 digit after it.
So I figured. But that's not what it does. Look up format specifier reference.
icarus31 wrote:The "str" variable was set to :
str[0] = 'f'
str[0] = '\x00'
str[1] = '\x91'
str[2] = '\x9C'
str[3] = '\x00'
str[4] = '\x00'
str[5] = '\x00'
str[6] = '\x00'
str[7] = '\x00'
str[8] = '\x00'
This appears to support BugMan's suggestion.
For those browsing this quickly and wanting to know why it printed what it did:
scifi wrote:
> icarus31 wrote:
> > The "str" variable was set to :
> >
> > str[0] = 'f'
> > str[0] = '\x00'
> >
> > "%3.1f"
> This appears to support BugMan's suggestion.
That was because the limited library scanned the print string, got to the "f", wasn't built for floats and thus converted "%f" to "f" in the buffer.
Tom
Hello,
If I can give an advice, if you can, you'd better switch to CW7.2.2, because there's big improvement between CW7.1 and CW7.2.
If you keep CW7.1, if I remember, you have to rebuild libraries to enable printf floating point support.
Hi,
If you use CW7.2, by librarian item, I meant Edit->"YourProject" Settings->Linker->Librarian.
You will find the same in CW10 : Project->Properties->C/C++ Build->Settings->tools settings->Librarian
Regards,
Emmanuel