-4

I have a value which is like this in C#:

14.995

I have tried storing the value inside these variables:

double Number;
float Number;

Both values seem to round up this number to 15 .. However, instead of 15... I'd like the number to be rounded to the exactly 14.99 :/

Number= Math.Round(amount * (1 - calcPerc),2,MidpointRounding.AwayFromZero);\

The output is always 15... Is there some way to round this to 14.99 instead of 15 ?

Can someone help me out?

User987
  • 3,663
  • 15
  • 54
  • 115
  • 1
    What are `amount` and `calcPerc` (values and data types)? Please give us a [mre] – DavidG Nov 26 '19 at 09:20
  • @HimBromBeere Not sure that's the right dupe, I'm more likely to believe this is converting to integer, but since OP isn't talking... – DavidG Nov 26 '19 at 09:31
  • Note that `MidpointRounding.AwayFromZero` means that when you have to round .5, it rounds it *away from zero*: .5 -> 1 // -.5 -> -1. You might prefer `MidpointRounding.ToZero` instead or check which option fits your needs [MidpointRounding](https://learn.microsoft.com/en-us/dotnet/api/system.midpointrounding?view=netframework-4.8) – Rafalon Nov 26 '19 at 09:39

3 Answers3

0

Assuming you want to truncate everything after the 2nd decimal place

decimal calcPerc = 14.995m;
decimal result = Math.Truncate(calcPerc * 100) / 100m; // 14.99

https://dotnetfiddle.net/eMtqKb

fubo
  • 44,811
  • 17
  • 103
  • 137
0

try this,

decimal Number= 14.995;

Math.Floor(Number* 100) / 100;

Developer
  • 89
  • 1
  • 14
-1

Please try this

double n = 14.995;
double newNum  = Math.Floor(n * Math.Pow(10, 2)) / Math.Pow(10, 2);

output is 14.99

Saif
  • 2,611
  • 3
  • 17
  • 37
  • Any reason to use `Math.Pow(10, 2)` and not `100`? – Rafalon Nov 26 '19 at 09:46
  • @Rafalon because it takes value and raise the value to specified power.. read this https://learn.microsoft.com/en-us/dotnet/api/system.math.pow?view=netframework-4.8 – Saif Nov 26 '19 at 09:54
  • I know how Math.Pow works, I just wonder why you have to perform this where you can simply write `100` – Rafalon Nov 26 '19 at 09:55
  • @Rafalon Technically, it's the same as writing `100d`, but yes, you're right. – DavidG Nov 26 '19 at 09:58
  • `Math.Floor` fails at negative numbers https://dotnetfiddle.net/OfxL75 – fubo Nov 28 '19 at 13:38