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

How to get two decimal places in C language

下次还敢
下次还敢Original
2024-04-27 23:24:451856browse

The methods to get two decimal places in C language are: use the format string printf("%.2f", number); use the rounding function round(number * 100) / 100; use truncation Function trunc(number * 100) / 100.

How to get two decimal places in C language

How to get two decimal places in C language

In C language, you can get it by the following method Two decimal places:

  1. Use format string

    <code class="c">#include <stdio.h>
    
    int main() {
        double number = 123.456789;
        printf("%.2f\n", number);  // 输出:123.46
        return 0;
    }</code>

    printf Format string in function%.2f specifies the precision of floating point number output to two decimal places.

  2. Using the rounding function

    <code class="c">#include <math.h>
    
    int main() {
        double number = 123.456789;
        number = round(number * 100) / 100;  // 舍入到小数点后两位
        printf("%.2f\n", number);  // 输出:123.46
        return 0;
    }</code>

    round The function rounds a number to the nearest integer. Multiply the number by 100 before rounding to only two decimal places.

  3. Use the truncation function

    <code class="c">#include <math.h>
    
    int main() {
        double number = 123.456789;
        number = trunc(number * 100) / 100;  // 截断到小数点后两位
        printf("%.2f\n", number);  // 输出:123.45
        return 0;
    }</code>

    trunc The function truncates the number and discards the decimal part. Multiply the number by 100 and then truncate it so that only the whole number remains after the decimal point.

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