-2

I have tried many Math function in the c# to convert 1.7272 to 1.73 but did not got any function working to achieve my goal. I wants a simple conversion which is 1.7272 to 1.73

Please suggest me which Math function can do work for me?

Thanks

user1301587
  • 455
  • 4
  • 11
  • 23
  • 2
    http://msdn.microsoft.com/en-us/library/aa340225%28v=vs.71%29.aspx o.O - hint hint: Math.Round( number, 2 ); // 2 decimals after – Najzero Feb 06 '13 at 13:37
  • http://stackoverflow.com/questions/257005/how-do-you-round-a-number-to-two-decimal-places-in-c – RobJohnson Feb 06 '13 at 13:38
  • 3
    Here's a custom converter: `if (value == 1.7272) { return 1.73; }` ? – Grant Thomas Feb 06 '13 at 13:38
  • @GrantThomas you gotta be kidding – fvu Feb 06 '13 at 13:39
  • this question is too common. `:D` http://stackoverflow.com/questions/257005/how-do-you-round-a-number-to-two-decimal-places-in-c – spajce Feb 06 '13 at 13:39
  • 2
    @fvu Kinda. If the question was worded that this would need to work for _any other value_, then perhaps I would have refrained. As it stands, the OP _always_ has a value of 1.7272 and _always_ wants it to turn into 1.73. I don't believe this to be true, mind you. But, generalise and use a literal example. – Grant Thomas Feb 06 '13 at 13:40
  • 1
    @GrantThomas: It certainly matches the spec, and would pass the unit test! – Jon Egerton Feb 06 '13 at 13:41
  • @GrantThomas I am sorry I miscredited ;-); I spent to much time with those nasty salesman people specifying stuff (like "its always x" ) and then complain if its outside the spec and misbehaving. You are right, always stick to the spec and fix unit-tests to run through :-D – Najzero Feb 06 '13 at 13:43

5 Answers5

4

You should use Math.Round:

Math.Round(1.7272, 2)
Dennisch
  • 6,888
  • 1
  • 17
  • 32
1

If you'd like a string

> (1.7272).ToString("#.##")
"1.73"

Or a decimal

> Math.Round(((Decimal)1.7272), 2)
1.73m
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
0

Math.Round(1.7272,2) is what you you are looking for...

Gopesh Sharma
  • 6,730
  • 4
  • 25
  • 35
0

The .Round function will help you

System.Math.Round(1.7272, 2) returns 1.73
Larry
  • 17,605
  • 9
  • 77
  • 106
0
double d = Math.Round(1.7272, 2);
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116