# Thread: Matlab to C Code Function for Roundup

1. ## Matlab to C Code Function for Roundup

Hi, I am trying to create a function for C Code based on my Matlab function for rounding up a value to a user-defined variable.

I understand that you can use the Ceil function to round up when using printf, but as I am not displaying a lot of my calculations in the console I am looking for another method.

Below is an example of what I am trying to acheive:

Any help would be greatly appreciated!

% Function to round up a number to the specified decimal place
function return_value = ROUNDUP(value, decimalPlaces)
% Round the incoming value
count = 0;
magnitude = 1;
for count = 0 : decimalPlaces
magnitude = magnitude * 10;
end
return_value = ceil((value * magnitude) / magnitude); 2. <math.h> has a function called round.

C - round() function - fresh2refresh.com 3. As usual, "Structure" doesn't even bother reading the question.
Code:
```double roundUpDecimalPlaces(double x, int decimalPlaces) {
double mag = 1.0;
for (int i = 0; i < decimalPlaces; ++i)
mag *= 10;
return ceil(x * mag) / mag;
}``` 4. Originally Posted by john.c As usual, "Structure" doesn't even bother reading the question.
Code:
```double roundUpDecimalPlaces(double x, int decimalPlaces) {
double mag = 1.0;
for (int i = 0; i < decimalPlaces; ++i)
mag *= 10;
return ceil(x * mag) / mag;
}```

Thanks John. Im new to c code and curious how How does double x pick up the value and should int decimalPlaces be float decimalPlaces?

Thanks! 5. How does double x pick up the value
You call the function with the initial value as that argument.

should int decimalPlaces be float decimalPlaces?
Of course not, unless you say, have some notion of half a decimal place or 0.34 of a decimal place. 6. Well... a better approach:
Code:
```/* Changed 'decimalPlaces' to 'unsigned int' to avoid 'negative'
values. Notice this value can still be very big, which will cause
problems! Still. This argument is a count of decimal places, so
it doesn't make any sense using a floating point type... */
double roundUpDecimalPlaces(double x, unsigned int decimalPlaces)
{
double mag;

/* Notice: 'decimalPlaces' will be converted to double when calling pow(). */
mag = pow(10.0, decimalPlaces);
return ceil(x * mag) / mag;
}```
But, of course, keep in mind that floating point is accurate, but not exact in most cases. Popular pages Recent additions count, function, magnitude, matlab, round 