You can safely cast the results of round or roundf to long. C also provides a function that does this for you, lround and lroundf. The round functions return the nearest integer in float format, it will not return something like 4.9999999, it will return a number that represents 5 exacts. Except... Floating point is weird, because of course it is. Floating point can't represent all integers exactly, and larger than positive or negative 224 for 32-bit floats and 253 for 64-bit doubles present problems. If your numbers are within a reasonable range then the above holds true. If your numbers are outside this range then unpredictable things may occur. Answer from daikatana on reddit.com
Top answer
1 of 2
4

First of all, you use the data type int, which cannot hold fractional values (and will implicitly round them towards zero, even before the function is ever called.) You should use double instead, since this is the proper datatype for fractional numbers.

You would also want to use the ceil(x) function, which gives the nearest whole number larger than or equal to x.

#include <math.h>

double calculateCharges(double hours)
{
  if (hours <= 3) {
    return 2.00;
  } else {
    // return $2.00 for the first 3 hours,
    //  plus an additional $0.50 per hour begun after that
    return 2.00 + ceil(hours - 3) * 0.50;
  }
}
2 of 2
0

To answer your query, you should study your variable type. You use hours as a in, but you return a 2.00 which is a floating number( aka not a integer)

#include <math.h>

double calculateCharge(double hours)
{ 
 //To use accurately the ceil function from Math, the parameter should be a double!
  double calculateTime = ( hours <3) ? 2 : (2+ceil(hours-3)*0.50); 
  return calculateTime;
}

Include the math.h header to be able to use the Math struc. It is a really help structure when you have to compute values, you can calculate the sinus of a number for instance. In our situation, the ceil function will always return the value to round up to the nearest integer. You can learn more about it here : http://www.techonthenet.com/c_language/standard_library_functions/math_h/ceil.php Oh and also, you said less than three hours, but in your function you say less or equals to 3. Make sure you actually use the good operator or you could end up with results you are not expecting while running your function!

Oh, you can look up the ternary operator there in order to have a better understanding of it since it's a bit obscure the first time :http://msdn.microsoft.com/en-us/library/ty67wk28.aspx

Hope it helps you :)

Top answer
1 of 11
17

To round a float in C, there are 3 <math.h> functions to meet the need. Recommend rintf().

float nearbyintf(float x);

The nearbyint functions round their argument to an integer value in floating-point format, using the current rounding direction and without raising the โ€˜โ€˜inexactโ€™โ€™ floating point exception. C11dr ยง7.12.9.3 2

or

float rintf(float x);

The rint functions differ from the nearbyint functions (7.12.9.3) only in that the rint functions may raise the โ€˜โ€˜inexactโ€™โ€™ floating-point exception if the result differs in value from the argument. C11dr ยง7.12.9.4 2

or

float roundf(float x);

The round functions round their argument to the nearest integer value in floating-point format, rounding halfway cases away from zero, regardless of the current rounding direction. C11dr ยง7.12.9.6 2


Example

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

void rtest(const char *fname, double (*f)(double x), double x) {
  printf("Clear inexact flag       :%s\n", feclearexcept(FE_INEXACT) ? "Fail" : "Success");
  printf("Set round to nearest mode:%s\n", fesetround(FE_TONEAREST)  ? "Fail" : "Success");

  double y = (*f)(x);
  printf("%s(%f) -->  %f\n", fname,x,y);

  printf("Inexact flag             :%s\n", fetestexcept(FE_INEXACT) ? "Inexact" : "Exact");
  puts("");
}

int main(void) {
  double x = 8.5;
  rtest("nearbyint", nearbyint, x);
  rtest("rint", rint, x);
  rtest("round", round, x);
  return 0;
}

Output

Clear inexact flag       :Success
Set round to nearest mode:Success
nearbyint(8.500000) -->  8.000000
Inexact flag             :Exact

Clear inexact flag       :Success
Set round to nearest mode:Success
rint(8.500000) -->  8.000000
Inexact flag             :Inexact

Clear inexact flag       :Success
Set round to nearest mode:Success
round(8.500000) -->  9.000000
Inexact flag             :Exact

What is weak about OP's code?

(int)(num < 0 ? (num - 0.5) : (num + 0.5))
  1. Should num have a value not near the int range, the cast (int) results in undefined behavior.

  2. When num +/- 0.5 results in an inexact answer. This is unlikely here as 0.5 is a double causing the addition to occur at a higher precision than float. When num and 0.5 have the same precision, adding 0.5 to a number may result in numerical rounded answer. (This is not the whole number rounding of OP's post.) Example: the number just less than 0.5 should round to 0 per OP's goal, yet num + 0.5 results in an exact answer between 1.0 and the smallest double just less than 1.0. Since the exact answer is not representable, that sum rounds, typically to 1.0 leading to an incorrect answer. A similar situation occurs with large numbers.


OP's dilemma about "The above line always prints the value as 4 even when float num =4.9." is not explainable as stated. Additional code/information is needed. I suspect OP may have used int num = 4.9;.


// avoid all library calls
// Relies on UINTMAX_MAX >= FLT_MAX_CONTINUOUS_INTEGER - 1
float my_roundf(float x) {
  // Test for large values of x 
  // All of the x values are whole numbers and need no rounding
  #define FLT_MAX_CONTINUOUS_INTEGER  (FLT_RADIX/FLT_EPSILON)
  if (x >= FLT_MAX_CONTINUOUS_INTEGER) return x;
  if (x <= -FLT_MAX_CONTINUOUS_INTEGER) return x;

  // Positive numbers
  // Important: _no_ precision lost in the subtraction
  // This is the key improvement over OP's method
  if (x > 0) {
    float floor_x = (float)(uintmax_t) x;
    if (x - floor_x >= 0.5) floor_x += 1.0f;
    return floor_x;
  }

  if (x < 0) return -my_roundf(-x);
  return x; //  x is 0.0, -0.0 or NaN
}

Tested little - will do so later when I have time.

2 of 11
16

4.9 + 0.5 is 5.4, which cannot possibly round to 4 unless your compiler is seriously broken.

I just confirmed that the Googled code gives the correct answer for 4.9.

marcelo@macbookpro-1:~$ cat round.c 
#include <stdio.h>

int main() {
    float num = 4.9;
    int n = (int)(num < 0 ? (num - 0.5) : (num + 0.5));
    printf("%d\n", n);
}
marcelo@macbookpro-1:~$ make round && ./round
cc     round.c   -o round
5
marcelo@macbookpro-1:~$
๐ŸŒ
Cplusplus
cplusplus.com โ€บ forum โ€บ beginner โ€บ 272936
Rounding up to the nearest integer - C++ Forum
my equation is the same as round(). From the sample code on our site: (see that -5.5 -> -6) Output: value round floor ceil trunc ----- ----- ----- ---- ----- 2.3 2.0 2.0 3.0 2.0 3.8 4.0 3.0 4.0 3.0 5.5 6.0 5.0 6.0 5.0 -2.3 -2.0 -3.0 -2.0 -2.0 -3.8 -4.0 -4.0 -3.0 -3.0 -5.5 -6.0 -6.0 -5.0 -5.0 if you want a different result, of course, you can do it a different way. Yours matches ceil(). ... round() doesn't state 'round up'. It states that it will round to 'the nearest integer'. so -2.3 rounds to -2 and -3.5 rounds to -4
๐ŸŒ
W3Schools
w3schools.com โ€บ c โ€บ ref_math_round.php
C Math round() Function
C Date C Random Numbers C Macros ... integer: printf("%f", round(0.60)); printf("%f", round(0.40)); printf("%f", round(5)); printf("%f", round(5.1)); printf("%f", round(-5.1)); printf("%f", round(-5.9)); Try it Yourself ...
๐ŸŒ
TechOnTheNet
techonthenet.com โ€บ c_language โ€บ standard_library_functions โ€บ math_h โ€บ ceil.php
C Language: ceil function (Ceiling)
In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ c round() function
C round() Function - Scaler Topics
March 27, 2024 - The round function accepts an argument that can be of any type from int, float, double or long double. It returns the closest integer value to that number. In the case of negative numbers, it will first convert the number into positive, and then it will apply the above logic to find the nearest integer to that number, and finally, it will again convert that integer to a negative integer and return a negative integer.
๐ŸŒ
Vultr
docs.vultr.com โ€บ clang โ€บ standard-library โ€บ math-h โ€บ ceil
C math.h ceil() - Round Up to Integer | Vultr Docs
September 27, 2024 - The ceil() function in the math.h library is an invaluable tool in C for rounding up floating-point numbers to the nearest integer. It guarantees upward rounding regardless of whether the number is positive or negative, providing a straightforward ...
Find elsewhere
๐ŸŒ
Quora
quora.com โ€บ How-does-one-round-floats-to-the-nearest-integer-in-C
How does one round floats to the nearest integer in C? - Quora
Answer (1 of 4): add 0.5 [code]#include int main(){ int i; i = 12.34; printf("%d\n", i); // 12 i = 12.34 + 0.5; printf("%d\n", i); // 12 i = 45.67; printf("%d\n", i); // 45 i = 45.67 + 0.5; printf("%d\n", i); // 46 } [/code]
๐ŸŒ
GNU
gnu.org โ€บ software โ€บ libc โ€บ manual โ€บ html_node โ€บ Rounding-Functions.html
Rounding Functions (The GNU C Library)
Preliminary: | MT-Safe | AS-Safe | AC-Safe | See POSIX Safety Concepts. These functions round x upwards to the nearest integer, returning that value as a double.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ c_standard_library โ€บ c_function_round.htm
C library - round() function
The C library round() function can be used to calculate the floating-point into the nearest integer. This function is a part of C99 standard and defined under the header math.h. Suppose we have a integer like 0.5 or above, the function round ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ round-function-in-c
round() Function in C - GeeksforGeeks
July 5, 2024 - C round() is a built-in library function that rounds a floating-point number to the nearest integer. If the fractional part of the number is 0.5 or greater, the argument is rounded away from zero.
๐ŸŒ
Cppreference
en.cppreference.com โ€บ w โ€บ c โ€บ numeric โ€บ math โ€บ round
round, roundf, roundl, lround, lroundf, lroundl, llround, llroundf, llroundl - cppreference.com
1-3) Computes the nearest integer value to arg (in floating-point format), rounding halfway cases away from zero, regardless of the current rounding mode.
๐ŸŒ
Cplusplus
cplusplus.com โ€บ reference โ€บ cmath โ€บ round
Round
Additional overloads are provided in this header (<cmath>) for the integral types: These overloads effectively cast x to a double before calculations (defined for T being any integral type). ... Value to round. The value of x rounded to the nearest integral (as a floating-point value).
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ round function in c
The Round Function in C | Delft Stack
March 12, 2025 - What is the round function in C? The round function in C rounds a floating-point number to the nearest integer.
๐ŸŒ
Tutorial Gateway
tutorialgateway.org โ€บ c-round-function
C round function
April 5, 2025 - In this program, We are going to find the closest integer value of different numbers and display the output. #include <stdio.h> #include <math.h> int main() { printf("\n The Round Value of 0.75 = %.2f ", round(0.75)); printf("\n The Round Value of 15.25 = %.2f ", round(15.25)); printf("\n The Round Value of 152.50 = %.2f ", round(152.50)); printf("\n The Round Value of -14.36 = %.2f ", round(-14.36)); printf("\n The Round Value of -26.82 = %.2f ", round(-26.32)); printf("\n The Round Value of -90.50 = %.2f \n", round(-90.50)); return 0; }