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.
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.
You can do it like this: printf("%. 6f", myFloat); 6 represents the number of digits after the decimal separator.
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.
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.
what happened to the good old %f
"%f"
example
printf("%f\n", floatVal);
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