Home > Mobile >  How to round DOWN to 2 decimal in C
How to round DOWN to 2 decimal in C

Time:10-16

So I am trying to round DOWN to 2 decimal places in C - EDIT: I actually need to change the value, not just display it to 2 decimals. For example:

double x = 0.1234;
x = 0.12;
    
double y = 3.14159;
y = 3.14;

Is the an integrated function in <math.h> similar to floor(), or is there another way to do this?

CodePudding user response:

If you want to display a float or double with 2 decimal places, specify a precision of 2 when using the %f format specifier.

printf("x=%.2f", x);

CodePudding user response:

Well I need to value to change so I used x = (double)((int)(x*100))/100;

This works, but you are limited to a relatively low range, i.e: 123456789 * 100 overflows.

Check if modf helps:

#include <stdio.h>
#include <math.h>

double dec2(double number)
{
    double fractpart, intpart;

    fractpart = modf(number, &intpart);
    return intpart   round(fractpart * 100) * 0.01;
}

int main(void)
{
    printf("%f\n", dec2(0.1234));
    printf("%f\n", dec2(3.14159));
    return 0;
}

Output:

0.120000
3.140000
  •  Tags:  
  • c
  • Related