1

I have float values from 00.00 to 99.99 range. I am trying to convert the float value to a string along with the conversion should remove decimal separator.

flaot a = 00.17;
float b = 08.56;

To remove decimal separator I am multiplying with *100 and converting to string using ftoa() function.

a = a*100;
b = b*100;

ftoa(a, 0, temp_string);
puts(temp_string); 
ftoa(b, 0, temp_string);

output is: 17, 856, 2898

My output string should look like this

output: 0017,0856,2898

I can add 0's to string with a condition whether the number is below 99 add two zero's and if above 99 and below 999 add one zero.

Is there any best method to do this work?

2

1 Answer 1

3

Using printf/sprintf you can state the width of a number you wish to print and therefore have leading 0s.

a = a*100;
b = b*100;
c = c*100;
printf ("a=%04.0f b=%04.0f", a, b);

gives:

a=0017 b=0856

See http://www.cplusplus.com/reference/cstdio/printf/ for more

sprintf will format a string instead of printing to stdout so you can then output this how you wish.

Sign up to request clarification or add additional context in comments.

4 Comments

mr_Alex_Nok_, To @Sourav Ghosh point, this answer could indicate the multiplication. e.g. printf ("a=%04.0f", a*100.0);. Note that *100 vs *100.0 could make a difference with values near xx.xx5. I recommend *100.0 for correctness in those edge cases.
sprintf(mystring, "%05d", myInt); is to lead zeros for integer. if i use same with sprintf(mystring, "%05s", tempString); then it only adding spaces not zeors?? not working for string
i am trying to build bigger string so i have to convert float to string and add lead zeros and then build string.
@verendra - you can do this easily with sprintf. Either as separate strings which you can then concatenate or as one long string. Be careful of string terminators '\0' or course

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.