-
Notifications
You must be signed in to change notification settings - Fork 16
Description
Proposed feature
I propose, that the printf precision option be made to also work with pseudo floating point numbers, represented by an integer type with an implicit (fixed) decimal exponent.
Example:
The value 3.14 could be represented (with two decimals precision) by an integer value of 314 (assuming an implicit decimal exponent of -2): 314 * 10^(-2) = 3.14
Note, that precision = -exponent
Current printf formatting design.
Proposed behavior
Using the standard "f" specifier, with an implicit float conversion: int_value * 10^(-precision)
printf("Pi = %.2f", 314); // result: "pi = 3.14"
printf("Amount $%.2f", 23456); // result: "Amount $234.56
It may be a good idea, to even support negative precision specifiers (positive decimal exponents):
printf("Rounded %.-2f", (byte) 123); // result: "Rounded 12300"
For backwards compatibility, it might be better to use a new "integer with decimal exponent" specifier, rather than repurposing the "f" specifier with an integer argument.
Motivation
On memory and CPU resource restricted MCUs like the AVRs used on the Arduino, it is common practice to avoid using floats to represent floating point values, like temperature, but instead use an integer data type, like an int, representing tenth of degrees. So a temperature of 45.6 would be represented by an integer value of 456, with an implicit decimal exponent (10^-2). Similarly, a monetary amount, e.g. $234.56 can be represented by an integer value, representing the number of cents: 23456, with an implicit decimal exponent (10^-2)
Such an "external/fixed 10^n exponent" implementation have several advantages over using native floating point data types:
- Low memory footprint (e.g. values -10.0 .. +10.0 with one decimal precision, or -1000 ..+1000 with -1 decimal precision, can be stored in a single byte).
- Calculations are much faster (less CPU cycles).
- No rounding issues when converting values to/from decimal (logging, displaying or inputting), as any number, with the chosen precision, can be accurately represented in the binary (integer) form.