Programing

C # Double-소수점 이하 두 자리이지만 반올림이없는 ToString () 형식

lottogame 2020. 6. 18. 07:51
반응형

C # Double-소수점 이하 두 자리이지만 반올림이없는 ToString () 형식


소수점 이하 두 자리 만 갖도록 C #에서 a Double어떻게 형식화 String합니까?

String.Format("{0:0.00}%", myDoubleValue)숫자를 사용 하면 반올림되고 반올림하지 않고 간단한 자르기를 원합니다. 또한 전환 String이 문화에 민감 해지기를 원합니다 .


나는 다음을 사용한다 :

double x = Math.Truncate(myDoubleValue * 100) / 100;

예를 들어 :

숫자가 50.947563이고 다음을 사용하면 다음이 발생합니다.

- Math.Truncate(50.947563 * 100) / 100;
- Math.Truncate(5094.7563) / 100;
- 5094 / 100
- 50.94

그리고 답을 잘랐습니다. 이제 문자열을 포맷하려면 다음을 수행하십시오.

string s = string.Format("{0:N2}%", x); // No fear of rounding and takes the default number format

다음 은 숫자를 반올림 하지만으로 인해 소수점 이하 2 자리까지 표시합니다 (마침표 0 제거) .##.

decimal d0 = 24.154m;
decimal d1 = 24.155m;
decimal d2 = 24.1m;
decimal d3 = 24.0m;

d0.ToString("0.##");   //24.15
d1.ToString("0.##");   //24.16 (rounded up)
d2.ToString("0.##");   //24.1  
d3.ToString("0.##");   //24

http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/


먼저 자른 다음 형식을 지정하는 것이 좋습니다.

double a = 123.4567;
double aTruncated = Math.Truncate(a * 100) / 100;
CultureInfo ci = new CultureInfo("de-DE");
string s = string.Format(ci, "{0:0.00}%", aTruncated);

2 자리 자르기에는 상수 100을 사용하십시오. 원하는 소수점 다음의 숫자만큼 1과 숫자 0을 사용하십시오. 서식 결과를 조정해야하는 문화권 이름을 사용하십시오.


가장 간단한 방법은 숫자 형식 문자열을 사용하는 것입니다.

double total = "43.257"
MessageBox.Show(total.ToString("F"));

나는 price.ToString("0.00")0을 얻는 데 사용 합니다.


이것은 나를 위해 일하고있다

string prouctPrice = Convert.ToDecimal(String.Format("{0:0.00}", Convert.ToDecimal(yourString))).ToString();

Kyle Rozendo가 표현한 c # 함수 :

string DecimalPlaceNoRounding(double d, int decimalPlaces = 2)
{
    d = d * Math.Pow(10, decimalPlaces);
    d = Math.Truncate(d);
    d = d / Math.Pow(10, decimalPlaces);
    return string.Format("{0:N" + Math.Abs(decimalPlaces) + "}", d);
}

반올림 한 다음 버려야 할 소수를 하나 더 추가하는 방법은 다음과 같습니다.

var d = 0.241534545765;
var result1 = d.ToString("0.###%");

var result2 = result1.Remove(result1.Length - 1);

나는 이것이 오래된 실이라는 것을 알고 있지만 방금 이것을해야했습니다. 다른 접근 방식은 효과가 있지만에 대한 많은 호출에 영향을 줄 수있는 쉬운 방법을 원했습니다 string.format. 따라서 Math.Truncate모든 통화에를 추가하는 것은 실제로 좋은 옵션이 아닙니다. 또한 일부 서식이 데이터베이스에 저장되어 있기 때문에 훨씬 더 나빠졌습니다.

Thus, I made a custom format provider which would allow me to add truncation to the formatting string, eg:

string.format(new FormatProvider(), "{0:T}", 1.1299); // 1.12
string.format(new FormatProvider(), "{0:T(3)", 1.12399); // 1.123
string.format(new FormatProvider(), "{0:T(1)0,000.0", 1000.9999); // 1,000.9

The implementation is pretty simple and is easily extendible to other requirements.

public class FormatProvider : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof (ICustomFormatter))
        {
            return this;
        }
        return null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (arg == null || arg.GetType() != typeof (double))
        {
            try
            {
                return HandleOtherFormats(format, arg);
            }
            catch (FormatException e)
            {
                throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
            }
        }

        if (format.StartsWith("T"))
        {
            int dp = 2;
            int idx = 1;
            if (format.Length > 1)
            {
                if (format[1] == '(')
                {
                    int closeIdx = format.IndexOf(')');
                    if (closeIdx > 0)
                    {
                        if (int.TryParse(format.Substring(2, closeIdx - 2), out dp))
                        {
                            idx = closeIdx + 1;
                        }
                    }
                    else
                    {
                        throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
                    }
                }
            }
            double mult = Math.Pow(10, dp);
            arg = Math.Truncate((double)arg * mult) / mult;
            format = format.Substring(idx);
        }

        try
        {
            return HandleOtherFormats(format, arg);
        }
        catch (FormatException e)
        {
            throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
        }
    }

    private string HandleOtherFormats(string format, object arg)
    {
        if (arg is IFormattable)
        {
            return ((IFormattable) arg).ToString(format, CultureInfo.CurrentCulture);
        }
        return arg != null ? arg.ToString() : String.Empty;
    }
}

Following can be used for display only which uses the property of String ..

double value = 123.456789;
String.Format("{0:0.00}", value);

To what is worth, for showing currency, you can use "C":

double cost = 1.99;
m_CostText.text = cost.ToString("C"); /*C: format as currentcy */

Output: $1.99


You could also write your own IFormatProvider, though I suppose eventually you'd have to think of a way to do the actual truncation.

The .NET Framework also supports custom formatting. This typically involves the creation of a formatting class that implements both IFormatProvider and ICustomFormatter. (msdn)

At least it would be easily reusable.

There is an article about how to implement your own IFormatProvider/ICustomFormatter here at CodeProject. In this case, "extending" an existing numeric format might be the best bet. It doesn't look too hard.


I had that problem with xamarin and solved with:

porcent.ToString("0.##"+"%")

Solution:

var d = 0.123345678; 
var stringD = d.ToString(); 
int indexOfP = stringD.IndexOf("."); 
var result = stringD.Remove((indexOfP+1)+2);

(indexOfP+1)+2(this number depend on how many number you want to preserve. I give it two because the question owner want.)


Also note the CultureInformation of your system. Here my solution without rounding.

In this example you just have to define the variable MyValue as double. As result you get your formatted value in the string variable NewValue.

Note - Also set the C# using statement:

using System.Globalization;  

string MyFormat = "0";
if (MyValue.ToString (CultureInfo.InvariantCulture).Contains (CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator))
   {
      MyFormat += ".00";
   }

string NewValue = MyValue.ToString(MyFormat);

참고URL : https://stackoverflow.com/questions/2453951/c-sharp-double-tostring-formatting-with-two-decimal-places-but-no-rounding

반응형