CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to CCS Technical Support

float to array

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
[email protected]



Joined: 28 Jul 2014
Posts: 38

View user's profile Send private message

float to array
PostPosted: Wed Apr 29, 2020 12:37 pm     Reply with quote

How can i convert a float into a char array ?

For example if i have a float val=779.324 how this can be converted and stored in a array ?
jeremiah



Joined: 20 Jul 2010
Posts: 1353

View user's profile Send private message

PostPosted: Wed Apr 29, 2020 1:11 pm     Reply with quote

You can use sprintf() to "print" the float to a string, but you have to ensure the character array is long enough to hold the result + null character.
Quote:

sprintf( )

Syntax:
sprintf(string, cstring, values...);
bytes=sprintf(string, cstring, values...)

Parameters:
string - is an array of characters.
cstring - is a constant string or an array of characters null terminated.
values - are a list of variables separated by commas. Note that format specifies do not work in ram band strings.

Returns:
Bytes is the number of bytes written to string.

Function:
This function operates like printf() except that the output is placed into the specified string. The output string will be terminated with a null. No checking is done to ensure the string is large enough for the data. See printf() for details on formatting



Code:

char str[20];
sprintf(str,"%f",val);



I have also provided a "poorman's" version of snprintf() if you want to tell the function the size of your character array to avoid overrunning memory:

https://www.ccsinfo.com/forum/viewtopic.php?t=53652&highlight=snprintf

Code:

#include "snprintf.h"

...

char str[20];
snprintf(str,20,"%f",val);
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group