How to Convert Decimal to 2 fraction. example I want to convert 10.5234 to 10.52 and if the fraction is 0 disappear the fraction and 4.3014 convert to 4.3
Asked
Active
Viewed 1,257 times
0
-
2`MyVariable.ToString("N:2")` – devqon Mar 28 '17 at 13:10
-
and what if it is integer? 4.0 or 4. or 4? target data type string? decimal point localized? – Cee McSharpface Mar 28 '17 at 13:12
-
Possible duplicate of [How do you round a number to two decimal places in C#?](http://stackoverflow.com/questions/257005/how-do-you-round-a-number-to-two-decimal-places-in-c) – PaulF Mar 28 '17 at 13:15
-
Or a duplicate of this : http://stackoverflow.com/questions/2453951/c-sharp-double-tostring-formatting-with-two-decimal-places-but-no-rounding – PaulF Mar 28 '17 at 13:18
3 Answers
1
You can use
String.Format("{0:0.##}", myNumber);
You can have a look at the Custom Numeric Format Strings documentation.
If you use C#6.0 or above, you can use string interpolation like this:
$"{myNumber:0.##}"
as suggested by Jeppe Stig Nielsen

Community
- 1
- 1

Thomas Ayoub
- 29,063
- 15
- 95
- 142
-
1Nowadays people use string interpolation instead, so that is `$"{myNumber:0.##}"`. – Jeppe Stig Nielsen Mar 28 '17 at 16:09
-
0
You can do it yourself like this:
double toConvert = 10.5234;
double converted = ((int)Math.round(toConvert * 100)) / 100.0;
It will round your number to two decimal places.

Václav Struhár
- 1,739
- 13
- 21
0
double NumberToRound1 = 10.5234;
double NumberToRound2 = 4.3014;
//You can use Math.Round as follow
Math.Round(NumberToRound1, 2);
Math.Round(NumberToRound2, 2);
Desired Output:

Community
- 1
- 1

Pranav_Systematix
- 355
- 2
- 8