How to round numbers on specific digits?

Hi,

I want to round given numbers to specific digits:
3.654 on digit 2 becomes 3.65
1.23456 on digit 4 becomes 1.2346
and so on.

I know that I could implement this by a function like

round_digits (double x, int y) { return (floor(x*10^y+0.5)/10^y); }
but I would like to know if something like this is already implemented in mathcore or mathmore?

liquidat

It depends what you are trying to do. If you are printing something out, ‘Form’ or ‘sprintf’ is what you are looking for

char line[100];
sprintf (line, "%.2f", variable);
cout << line << endl;

or (preferably)

cout << Form(%.2f", variable);

If you are talking about rounding for doing calculations, the answer is more simple. You don’t. :smiley:

Cheers,
Charles

Thanks for the answer - the intention was more a kind of sorting the data in a kind of histogram, but it then turned out the the whole approach was not well chosen.

I changed the code background and do not need a rounding any more (fortunately).

Nevertheless, thanks for the answer :slight_smile:

liquidat

[quote=“liquidat”]Thanks for the answer - the intention was more a kind of sorting the data in a kind of histogram, but it then turned out the the whole approach was not well chosen.
[/quote]

This kind of situation is exactly where you do not want to round. :smiley:

Charles