Home > Backend Development > C++ > How to express keeping three decimal places in C language

How to express keeping three decimal places in C language

下次还敢
Release: 2024-05-02 19:24:44
Original
1124 people have browsed it

How to retain three decimal places in C language: use the printf() function; use the format specifier %.3f, where the number followed by . specifies the number of decimal places, and f represents a floating point number.

How to express keeping three decimal places in C language

Representation method with three decimal places in C language

In C language, you can format it by Input/output function printf() to retain a specified number of decimal places after the decimal point. The specific method is as follows:

Use %.3f format specifier

%.3f format specifier is used to specify The format of decimals to print, where:

  • . The number following specifies the number of digits after the decimal point.
  • f represents a floating point number (decimal).

Example:

<code class="c">#include <stdio.h>

int main() {
  float number = 123.4567;

  printf("%.3f", number);  // 输出:123.457

  return 0;
}</code>
Copy after login

Example output:

<code>123.457</code>
Copy after login

Other notes

  • If the actual number of digits after the decimal point is less than the specified number, it will be padded with 0s.
  • If the actual number of digits after the decimal point is more than the specified number, the excess digits will be truncated.
  • For negative numbers, the rules for retaining the decimal point are the same as for positive numbers.

The above is the detailed content of How to express keeping three decimal places in C language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template