In the C language function printf, to omit the last 0 of the decimal point when displaying a real number

Asked 1 years ago, Updated 1 years ago, 397 views

Execute the code below to get 0.100000 output.
Do not want to display the 00000 that follows the end of this output.
Specifically, I would like to print like 0.1.

#include<stdio.h>

int main() {
    double a = 0.1;
    printf("%f", a);
    return 0;
}

c

2023-01-07 23:31

3 Answers

For example, by changing the formatting of printf as shown below, the output can be up to the first decimal place.
(Note that 0 is not omitted because it is only a number of digits.)

printf("%.1f", a);


2023-01-08 00:59

Some values can be exponential, but you can remove the last 0 in %g for example question statements.
http://tpcg.io/_EEY22Z

printf("%g", a);


2023-01-08 02:23

To remove the decimal number 0, you might want to specify g as the translation specifier.
If it is more than the accuracy, it will be indicated in the index, so I think it is better to specify a certain amount of accuracy.
The following example specifies 16 for accuracy.

printf("%.16g\n", a);

Quotation from Manpage of PRINTF.

Translation specifier
g,G
Convert the double argument to the format f or e (F or E for G conversion). Accuracy specifies the number of digits to be displayed. If no precision is specified, it is considered six digits. If the accuracy is 0, it is considered a single digit. An e-form is used when the index of the value to be converted is less than -4 or greater than or equal to precision. A trailing zero of the decimal part of the converted result is deleted.Decimal points appear only if there is at least one decimal place.


2023-01-08 03:56

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.