0

I have tried using the ceil function but it rounds it to the nearest integer. My program aims to round a price of a subscription off to the nearest 0.05, for example 19.83 to 19.85, or nearest 0.1, for example 19.88 to 19.90

How would I go about this?

ninjedi
  • 27
  • 3
  • You would do some lateral thinking. Note that the specific value `0.1` cannot be represented exactly with the standard types `double` and `float` in in most implementations of C. – Jongware Oct 16 '15 at 08:31
  • Great explanation for the problems occuring when you have to multiply and re-divide: http://stackoverflow.com/questions/829067/how-can-i-round-a-float-value-to-2-post-decimal-positions – flowit Oct 16 '15 at 08:33
  • I'm afraid I don't quite understand because I'm rather new in C, could you explain further? – ninjedi Oct 16 '15 at 08:33
  • (In case that was directed to me) You cannot represent `0.1` *exactly* in a `double` or `float`, just as you cannot represent `1/3` *exactly* in decimal notation. – Jongware Oct 16 '15 at 08:37
  • 1
    seems like searching for "round to multiple" yields usable code like http://stackoverflow.com/questions/3407012/c-rounding-up-to-the-nearest-multiple-of-a-number – stijn Oct 16 '15 at 08:40

2 Answers2

2

Multiply by something, round, and then re-divide.

Something is left as an exercise (hint : it is related to the "nearest").

Jean-Michaël Celerier
  • 7,412
  • 3
  • 54
  • 75
0

For your example:

Double ex = 19.88;
Double ex2;
Double ex3;

ex2 = ex * 100;

If ( ex2 % 50  >= 25 )
{
ex2 = ex2 + 50 - ( ex2 % 50 );  // Rounding up
}
Else
{
ex2 = ex2 - ( ex2 % 50);   // rounding down
}

ex = ex2 / 100;

For further learning:

By multiplying ex by 100, you ensure that its a whole number. Now, if you do number % (modulo) anything, it will return whats left after you divide through anything. ex2 % 50 essentially does this. Now its only a case of properly rounding up or down.

Magisch
  • 7,312
  • 9
  • 36
  • 52
  • thank you, but is it possible to achieve what I want with the ceil function or is that limited to only rounding numbers off to the nearest integer? – ninjedi Oct 16 '15 at 08:37
  • `ceil(Double f)` will only round up. to the next integer value. So 19.88 becomes 20. – Magisch Oct 16 '15 at 08:39
  • okay, thank you so much! – ninjedi Oct 16 '15 at 08:39
  • @ninjedi If you are interested in uses for `ceil(Double f)` have a read here: http://www.tutorialspoint.com/c_standard_library/c_function_ceil.htm – Magisch Oct 16 '15 at 08:41