Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to nicely format floating numbers to String without unnecessary decimal 0?

Tags:

c#

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...)

like image 647
yu yang Jian Avatar asked May 17 '16 06:05

yu yang Jian


3 Answers

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

like image 26
user3345546 Avatar answered Oct 03 '22 22:10

user3345546


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();  
like image 64
Jcl Avatar answered Oct 04 '22 00:10

Jcl


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
        }
    }
}
like image 44
Darshan Faldu Avatar answered Oct 03 '22 22:10

Darshan Faldu