Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string format for printf floating point values

I have a question about using printf.

char str[8];
float val = 2.334563;
sprintf(str, format, val);
printf("val = %s.\n", str);

val = -23.34563;
sprintf(str, format, val);
printf("val = %s.\n", str);

val = -0.02334563;
sprintf(str, format, val);
printf("val = %s.\n", str);

val = 233;
sprintf(str, format, val);
printf("val = %s.\n", str);

The expected output follows:

val = +2.3345
val = -23.345
val = -0.0233
val = +233.00

What format string do I need for that? Thank you for your attention.

like image 539
user1020803 Avatar asked Oct 30 '11 15:10

user1020803


People also ask

Is a format string for float values?

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 %. 2f, f is for floating point number, which includes both double and float data type in Java.

How do I printf a float value?

You can do it like this: printf("%. 6f", myFloat); 6 represents the number of digits after the decimal separator.

What do you use in printf () to display a floating point value?

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.

What is the format string for scan or print a floating point number?

Some of the most commonly used placeholders follow: %a : Scan a floating-point number in its hexadecimal notation. %d : Scan an integer as a signed decimal number.


2 Answers

what happened to the good old %f

like image 105
Alok Save Avatar answered Oct 16 '22 03:10

Alok Save


"%f"

example

printf("%f\n", floatVal);
like image 26
Shamim Hafiz - MSFT Avatar answered Oct 16 '22 04:10

Shamim Hafiz - MSFT