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?

verendra
  • 223
  • 3
  • 18
  • I suggest to use a a printf that adds leading 0. See https://stackoverflow.com/questions/153890/printing-leading-0s-in-c – Jonny Schubert Jan 08 '19 at 13:34
  • Will `float` values always be near `xx.yy000...`, in which case [this good answer](https://stackoverflow.com/a/54093108/2410359) suffices. But if you want the best answer for values near ``xx.yy5000...`, additional work is needed. – chux - Reinstate Monica Feb 22 '19 at 07:56

1 Answers1

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.

  • mr_Alex_Nok_, To [@Sourav Ghosh](https://stackoverflow.com/questions/54092837/converting-float-value-to-string-without-decimal-separator#comment95018632_54093108) 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. – chux - Reinstate Monica Jan 08 '19 at 14:09
  • 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 – verendra Jan 08 '19 at 14:23
  • i am trying to build bigger string so i have to convert float to string and add lead zeros and then build string. – verendra Jan 08 '19 at 14:25
  • @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 – mr_Alex_Nok_ Jan 08 '19 at 14:29