I found interesting format for printing nonterminated fixed length strings like this:
char newstr[40] = {0}; sprintf(newstr,"%.*s", sizeof(mystr), mystr);
So I think maybe is there a way under printf command for printing a float number...
"%8.2f"
to have ability to choose number of decimals with integer number.
Something like this:
sprintf(mystr, "%d %f", numberofdecimals, floatnumbervalue)
String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.
we now see that the format specifier "%. 2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places. Similarly, had we used "%. 3f", x would have been printed rounded to 3 decimal places.
In C, there is a format specifier in C. To print 4 digits after dot, we can use 0.4f in printf().
You can also use ".*"
with floating points, see also http://www.cplusplus.com/reference/cstdio/printf/ (refers to C++, but the format specifiers are similar)
.number: For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
...
.*: The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
For example:
float floatnumbervalue = 42.3456; int numberofdecimals = 2; printf("%.*f", numberofdecimals, floatnumbervalue);
Output:
42.35
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With