Reputation: 289
I have code in VB.net in below:
me.Index = Format(Convert.ToDouble(g.Trim()), "##.##")
result : 120.00
how do i same thing in C#. I don't use format function in C#. I just want result will not place more then two value after point. i mean if i send value 120.120000 then result will be 12.12
Upvotes: 0
Views: 2607
Reputation:
You can do it like this,
decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);
Upvotes: 0
Reputation: 1059
Either you use this
var value = 2.346;
var str = value.ToString("0.00");
or
decimal.Round(yourValue, 2, MidpointRounding.AwayFromZero);
//as in msdn site which rounds a decimal value to a specified precision.
or use Round function like this
decimal a = 1.994444M;
Math.Round(a, 2);
Upvotes: 0
Reputation: 1500665
It's not clear what you mean by "I don't use format function in C#" but of course you could use string.Format
. However, using double.ToString
would probably be simpler:
Index = Convert.ToDouble(g.Trim()).ToString("0.##");
(I've changed the leading ##
to 0
to ensure that there's always a leading digit, so you don't get ".5" for example. Obviously if you really want the leading digits to be optional, change it to "#.##"
. I don't see a benefit in using ##
as a prefix though.)
However:
.
?double
at all. Are you sure you shouldn't be using decimal
?Upvotes: 3