mirror of
https://github.com/peter-tanner/neptunium-firmware.git
synced 2024-11-30 20:10:19 +08:00
33 lines
1.0 KiB
C
33 lines
1.0 KiB
C
#include "utils.h"
|
|
|
|
// https://stackoverflow.com/questions/23191203/convert-float-to-string-without-sprintf
|
|
char *float_to_char(float x, char *p)
|
|
{
|
|
char *s = p + FLOAT_CHAR_BUFF_SIZE; // go to end of buffer
|
|
uint16_t decimals; // variable to store the decimals
|
|
int units; // variable to store the units (part to left of decimal place)
|
|
if (x < 0)
|
|
{ // take care of negative numbers
|
|
decimals = (int)(x * -100) % 100; // make 1000 for 3 decimals etc.
|
|
units = (int)(-1 * x);
|
|
}
|
|
else
|
|
{ // positive numbers
|
|
decimals = (int)(x * 100) % 100;
|
|
units = (int)x;
|
|
}
|
|
|
|
*--s = (decimals % 10) + '0';
|
|
decimals /= 10; // repeat for as many decimal places as you need
|
|
*--s = (decimals % 10) + '0';
|
|
*--s = '.';
|
|
|
|
while (units > 0)
|
|
{
|
|
*--s = (units % 10) + '0';
|
|
units /= 10;
|
|
}
|
|
if (x < 0)
|
|
*--s = '-'; // unary minus sign for negative numbers
|
|
return s;
|
|
} |