programing

C# Double - ToString() 형식으로 소수점 두 자리를 사용하지만 반올림하지 않음

instargram 2023. 9. 14. 21:39
반응형

C# Double - ToString() 형식으로 소수점 두 자리를 사용하지만 반올림하지 않음

포맷은 어떻게 하나요?Double에 이르기까지String소수점 두 자리만 가지도록 C#에서?

사용하면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);

상수 100은 2자리 자르기에 사용합니다. 1 다음에 소수점 뒤에 숫자만큼 0을 사용합니다.서식 결과를 조정하는 데 필요한 문화 이름을 사용합니다.

사용합니다price.ToString("0.00")선두 0점을 얻은 것에

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

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

저는 Xamarin Forms에 대한 문제를 해결하고 이 문제를 해결했습니다.

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

반올림할 소수점 하나를 더해서 버리는 것은 어떨까요?

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

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

카일 로젠도(Kyle Rozendo)가 표현한 c# 함수:

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

이게 저한테 효과가 있어요.

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

이것이 오래된 실이라는 것을 알지만 나는 단지 이것을 해야만 했습니다.여기서 다른 접근 방식들은 효과가 있지만, 저는 많은 통화에 영향을 줄 수 있는 쉬운 방법을 원했습니다.string.format. 그래서 여기에.Math.Truncate모든 전화에 대해 좋은 선택은 아니었습니다.또한 일부 포맷이 데이터베이스에 저장되면서 더욱 악화되었습니다.

그래서 포맷 문자열에 잘라내기를 추가할 수 있는 사용자 지정 포맷 프로바이더를 만들었습니다.

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

구현은 매우 간단하며 다른 요구사항으로 쉽게 확장할 수 있습니다.

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;
    }
}

가치가 있는 것, 통화를 보여주기 위해서, 당신은"C":

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

출력:$1.99

IFformatProvider를 직접 작성할 수도 있지만, 결국 실제 잘라내기를 수행할 방법을 생각해야 할 것 같습니다.

.NET Framework는 사용자 지정 포맷도 지원합니다.여기에는 일반적으로 IformatProvider와 IcustomFormatter를 모두 구현하는 포맷 클래스의 작성이 포함됩니다.(msdn)

적어도 쉽게 재사용할 수 있을 겁니다.

자체 IFformatProvider를 구현하는 방법에 대한 기사가 있습니다.Code Project에서 Matter를 맞춤 제작합니다.이 경우 기존 숫자 형식을 "확장"하는 것이 가장 좋습니다.너무 딱딱해 보이지 않습니다.

String의 속성을 사용하는 디스플레이에만 다음을 사용할 수 있습니다.

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

또한 시스템의 Culture Information(문화 정보)도 기록합니다.여기 내 해결책은 반올림 없이.

이 예제에서는 변수 MyValue를 이중으로 정의하기만 하면 됩니다.결과적으로 문자열 변수 NewValue에 포맷된 값이 표시됩니다.

참고 - 문장을 사용하여 C#도 설정합니다.

using System.Globalization;  

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

string NewValue = MyValue.ToString(MyFormat);

해결책:

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

(indexOfP+1)+2(이 숫자는 보존할 숫자에 따라 달라집니다.질문 주인이 원하기 때문에 2개를 드립니다.)

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

반응형