Home  >  Article  >  Backend Development  >  How to get two decimal places in C language

How to get two decimal places in C language

下次还敢
下次还敢Original
2024-05-02 19:15:53693browse

In C language, the steps to take two decimal places: multiply the floating point number by 100 and move the decimal point two places to the right. Round the result and discard the part after the decimal point. Divide the rounded result by 100 to obtain a floating-point number with two decimal places.

How to get two decimal places in C language

How to use C language to get two decimal places

In C language, you can use the following steps to get the decimal point The last two digits:

  1. Multiply by 100: Multiply the floating point number by 100 and move the decimal point two places to the right.
  2. Rounding: Round the result and discard the part after the decimal point.
  3. Divide by 100: Divide the rounded result by 100 to obtain a floating point number with two decimal places.

Code example:

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

int main() {
    float number = 123.456;

    // 乘以 100,将小数点向右移动两位
    int tmp = number * 100;

    // 取整,舍弃小数点后的部分
    int rounded = tmp / 1;

    // 除以 100,得到保留两位小数的浮点数
    float rounded_number = (float)rounded / 100;

    // 输出结果
    printf("原浮点数:%f\n", number);
    printf("保留两位小数的浮点数:%f\n", rounded_number);

    return 0;
}</code>

Output:

<code>原浮点数:123.456001
保留两位小数的浮点数:123.45</code>

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

Statement:
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