3 ms·
In my work life, I have a problem where I have to interface with a stringly typed API. For instance, characters 20-25 in a 400 byte string are a floating point
by nwallin 7y ago
In my work life, I have a problem where I have to interface with a stringly typed API. For instance, characters 20-25 in a 400 byte string are a floating point number. No it's not a good API but I don't make decisions. So you need a six character float. "12" is wrong because it's two characters, also "12<four spaces>" is invalid. "1.2e01" is wrong compared to "12.000" because it has (many) more significant digits. ".00001" is wrong compared to "1.2e-5".
I don't know how to solve this problem. printf doesn't cut it. It simply can't specify an exact number of characters.
- BeeOnRope 7y agoYou could try: %06.*g for width 6 down to 1. I believe this will always find an answer, and the one with the largest number of significant digits. For example: void format(double val, int width, char* buf) { for (int w = width; w > 0; w--) { int count = sprintf(buf, "%06.*g", w, val); if (count == width) return; } } "Working" example (unsafe, exits on failure, etc): https://godbolt.org/z/WiaPkT https://godbolt.org/z/WiaPkT Note that you can't represent negative values equal or below -1e-100 since those take 7 characters.