0

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?

Nox5692
  • 150
  • 8
  • 1
    Is your goal to round or to display 2 decimal? – CGi03 Oct 15 '22 at 14:02
  • @CGi03 Well now that you said that, routing down to 2 decimals is just displaying 2 decimals, so yes, just display 2 decimals. – Nox5692 Oct 15 '22 at 14:04
  • 1
    `printf("%.2f", 1.23456789);` – CGi03 Oct 15 '22 at 14:06
  • @CGi03 Well I need to value to change so I used x = (double)((int)(x*100))/100; – Nox5692 Oct 15 '22 at 14:07
  • There is a family of [`round`](https://linux.die.net/man/3/round) functions also. (But if you always want to "round down", then `floor` or `trunc` is what you want.) – Steve Summit Oct 15 '22 at 18:23
  • Beware that the numbers `0.12` and `3.14` [do not exist in binary floating point](https://stackoverflow.com/questions/1089018). So even after rounding, it may be important to specify `%.2f` when printing. Here's an example: `float f = 123.456; printf("%f\n", f); f = round(f * 100) / 100; printf("%f\n", f); printf("%.2f\n", f);` – Steve Summit Oct 15 '22 at 18:32

2 Answers2

1

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
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • `round(fractpart * 100)` will not do the **round DOWN** as in the title for all `number`. Perhaps the question title needs changing as this answer was accepted as is. – chux - Reinstate Monica Nov 06 '22 at 22:12
0

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);
dbush
  • 205,898
  • 23
  • 218
  • 273