Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printf variable number of decimals in float

Tags:

c

printf

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) 
like image 261
Wine Too Avatar asked May 07 '13 07:05

Wine Too


People also ask

How do you print float up to 2 decimal places?

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 %.

How do I print decimals using printf?

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.

How do I set precision in printf?

In C, there is a format specifier in C. To print 4 digits after dot, we can use 0.4f in printf().


1 Answers

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 
like image 178
Andreas Fester Avatar answered Sep 21 '22 22:09

Andreas Fester