-2

I did some search on the net. However, there is no solution for those case below.

if the value is less than or equal to 5, drop it and all the digits to the right of it.

if the value is greater than 5, increase by 1 the number to be rounded.

123.4561235 round to 123.456123.

123.4561236 round to 123.456124.

Is there any way to do so?

Anton Savin
  • 40,838
  • 8
  • 54
  • 90
Michael D
  • 1,449
  • 5
  • 18
  • 31
  • 2
    You can't round floating-point variables to specific numbers of decimal places. They don't *have* decimal places. – user207421 Nov 06 '14 at 07:48
  • @EJP it's not a duplicate, OP has very special rounding rules. – Anton Savin Nov 06 '14 at 07:52
  • Is there any reason you have these very special rounding rules? – Anton Savin Nov 06 '14 at 07:52
  • It is the rounding rule for trade price of the swap transaction that vendor is used. I need to follow the same rule – Michael D Nov 06 '14 at 07:54
  • 4
    @MichaelD Please tell me you're *not* really using floating-point numbers to represent money. They are fundamentally imprecise, something you cannot afford with money (and prices). *Always* use a fixed-point representation for that. Not to mention the fact that monetary applications seldom need the primary property of floating numbers - dynamic range of magnitude. – Angew is no longer proud of SO Nov 06 '14 at 07:59
  • You are right. However, the trade price for swap is a bit different from stock and future. Anyway it is just a checking tool. – Michael D Nov 06 '14 at 08:03
  • 1
    @MichaelD You're going to leak/virtually creating cent after cent. – πάντα ῥεῖ Nov 06 '14 at 08:04
  • @Angew Unfortunately, large parts of the trading world were asleep when that clue was handed out. – molbdnilo Nov 06 '14 at 09:30
  • @Angew It is not so much that binary floating point is inherently more or less precise than decimal. The key point is that decimal representations, including integer with a power-of-ten scale factor, are much better at representing terminating decimal fractions exactly. – Patricia Shanahan Nov 06 '14 at 15:05
  • @PatriciaShanahan I never said anything about binary vs. decimal. I mentioned floating vs. fixed. I don't think a floating-point decimal representation would be much better than a floating-point binary one in regards to monetary precision. – Angew is no longer proud of SO Nov 06 '14 at 15:13

1 Answers1

0

OK here you go.
Disclaimer: I haven't tested this thoroughly. Don't use this in the production code, and especially for money (you shouldn't use floating point for money at all).

double specialRound(double x, int precision) {
    return std::round((static_cast<long long>(x * std::pow(10.0, precision + 1)) - 1) / 10.0 + 0.05) 
         / std::pow(10.0, precision);
}

Demo

Anton Savin
  • 40,838
  • 8
  • 54
  • 90