0

I need to convert my value 2.8634 to 2.8. I tried the following ,

var no = Math.Round(2.8634,2,MidpointRounding.AwayFromZero)

I'm getting 2.87.

Suggest me some ideas how to convert.

Thanks

Buddy
  • 10,874
  • 5
  • 41
  • 58
shalusri
  • 13
  • 5

3 Answers3

5

This might do the trick for you

decimal dsd = 2.8634m;
var no = Math.Truncate(dsd * 10) / 10;

Math.Truncate calculates the integral part of a specified decimal number. The number is rounded to the nearest integer towards zero.

You can also have a look on the difference between Math.Floor, Math.Ceiling, Math.Truncate, Math.Round with an amazing explanation.

Community
  • 1
  • 1
Mohit S
  • 13,723
  • 6
  • 34
  • 69
0

Use this one.Hope this will work for you.

var no = Math.Round(2.8634,1,MidpointRounding.AwayFromZero)
Buddy
  • 10,874
  • 5
  • 41
  • 58
Shahzad Riaz
  • 354
  • 1
  • 6
0

It's a tad more cryptic (but more efficient) than calling a Math method, but you can simply multiply the value by 10, cast to an integer (which effectively truncates the decimal portion), and then divide by 10.0 (or 10d/10f, all just to ensure we don't get integer division) to get back the value you are after. I.e.:

float val = 2.8634;
val = ((int)(val * 10)) / 10.0;
soupdog
  • 335
  • 2
  • 9