Home > Software design >  Display decimal number
Display decimal number

Time:11-03

somebody know how to represent the digits to the left of the decimal point? I want to display the number 5 digits left to the point and 4 digits right to it/ for the exercise 12345/100 i want to get 00123.4500

CodePudding user response:

printf("0.4f", (double)12345/100);

man 3 printf says:

The overall syntax of a conversion specification is:

%[$][flags][width][.precision][length modifier]conversion

.4 means the floating point precision to print 4 decimals.

0 is a flag that means to pad with 0s.

10 is the width. If at the right of the decimal there are 4, and at the left there are 5, the total is 10 (with the dot).

CodePudding user response:

While the answer of alinsoar is correct and the most common case, I would like to mention another possibility which sometimes is useful: fixed-point representation.

An uint32_t integer holds 9 decimal digits. We may choose to imagine a decimal point before the 4th digit from the right. The example would then look like this:

#include <stdint.h>
#include <stdio.h>
#include <inttypes.h>

int main(void)
{
    uint32_t a = 123450000;   // 12345.0000
    uint32_t b = a / 100;     //   123.4500
    uint32_t i = b / 10000;   // integer part
    uint32_t f = b % 10000;   // fractional part
    printf("" PRIu32 "." PRIu32, i, f);  // 5 integer digits, 4 fractional digits 
}

Using fixed-point one has to pay special attention to the value range and e.g. multiplication needs special handling, but there are cases where it is preferable over the floating-point representation.

  •  Tags:  
  • c
  • Related