I have the same problem as HERE, but I'm using C#,
How to do it in C#?
(if use Tostring("F") as Here, all float number will turn into X.XX, also 0 to 0.00)
Here's an example float numbers
232.00000000
0.18000000000
1237875192.0
4.5800000000
0.00000000
1.23450000
What I want to turn them into:
232
0.18
1237875192
4.58
0
1.2345
Edit
(I suddenly find what I want to do is more complicate than above but it's too late to modify the question, maybe I'll ask it in another question...)
Use the String.Format()
method to remove trailing zeros from floating point numbers.
for example:
float num = 23.40f;
Console.WriteLine(string.Format("{0}",num));
It prints 23.4
You can use the 0.############
format. Add as many #
as decimal places you think you may have (decimals will be rounded off to those many places):
string output = number.ToString("0.############");
Sample fiddle: https://dotnetfiddle.net/jR2KtK
Or you can just use the default ToString()
, which for the given numbers in en-US culture, should do exactly what you want:
string output = number.ToString();
You have to create your own extension method something link this....
Extension Method
namespace myExtension
{
public static class myMath
{
public static double myRoundOff(this double input)
{
double Output;
double AfterPoint = input - Math.Truncate(input);
double BeforePoint = input - AfterPoint;
if ((Decimal)AfterPoint == Decimal.Zero && (Decimal)BeforePoint == Decimal.Zero)
Output = 0;
else if ((Decimal)AfterPoint != Decimal.Zero && (Decimal)BeforePoint == Decimal.Zero)
Output = AfterPoint;
else if ((Decimal)AfterPoint == Decimal.Zero && (Decimal)BeforePoint != Decimal.Zero)
Output = BeforePoint;
else
Output = AfterPoint + BeforePoint;
return Output;
}
}
}
Call your Extension Method
using myExtension;
namespace yourNameSpace
{
public partial class YourClass
{
public void YourMethod
{
double d1 = 232.00000000.myRoundOff(); // ANS -> 232
double d2 = 0.18000000000.myRoundOff(); // ANS -> 0.18
double d3 = 1237875192.0.myRoundOff(); // ANS -> 1237875192
double d4 = 4.5800000000.myRoundOff(); // ANS -> 4.58
double d5 = 0.00000000.myRoundOff(); // ANS -> 0
double d6 = 1.23450000.myRoundOff(); // ANS -> 1.2345
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With