Skip to content

koendv/FloatToAscii

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

FloatToAscii

Fast and small IEEE754-single precision float to string conversion, suitable for embedded systems.

  • small. about 2 to 3 kbyte.
  • checks for buffer overflows
  • fast. Does not use float or double. It's all integer math and table lookups.
  • plain c, no dependencies
  • c++ wrapper for Arduino

use

FloatToAscii can be used as an Arduino library or as plain C code.

arduino

Add the FloatToAscii library to your sketch using the library manager.

String &FloatToAscii(String &s, float f, int precision = 2);
  • Converts a float f to characters in the String s.
  • precision is the number of decimal places.
  • If precision is not given, prints two decimal places.
  • If precision is negative, prints all significant digits.
  • Uses modify-in-place of String s to avoid memory fragmentation.
  • Returns String s with the converted float.

Code:

float f = 6.02214076e23f;
String s;
Serial.print(FloatToAscii(s, f));

plain C

Copy src/ftoa.h and src/ftoa.c to your project. There are no library dependencies.

uint32_t ftoa(char *s, size_t size, float f, int32_t precision);

The ftoa() function converts a floating point number f into a character string s. ftoa() checks for buffer overflow.

  • s is the address of a buffer. At most size bytes will be written.
  • f is a 32-bit single precision IEEE754 floating point number.
  • precision is the the number of digits to appear after the decimal point. If precision is negative, all digits are printed, and sscanf() of the printed output produces the original float.
  • Upon successful return, returns the number of characters printed (minus terminating 0).

Code:

float f = 6.02214076e23f;
char s[20];
int len = ftoa(s, sizeof(s), f, -1);
printf("%s", s);

ftoa() prints fixed point for numbers between 1000000 and 0.0001, scientific format otherwise.

comparison

ftoa() uses the Grisu algorithm to convert a float to an ascii string. Various tests:

The Grisu algorithm to print floats looks like something you could implement in an fpga.

credits

Florian Loitsch proposed the Grisu algorithm and wrote the double-precision dtoa() version. Peter Barfuss converted dtoa() to 32-bit single-precision ftoa(). I would like to thank Florian Loitsch for his helpful comments.

About

Fast IEEE754-single precision to string conversion routine

Resources

License

Stars

Watchers

Forks

Packages

No packages published