2014-11-11 5 views
0

의 nullable decimal 변수에 저장하는 반올림없이 10 진수 값을 소수 자릿수 4 개로 형식화 (잘림)하려고했습니다. 예를 들어, 나는 (31.8182 반올림 NOT)10 진수 값 서식 지정 방법 C#

31.8181 

31.818181818181818181818181818M or 31.818181818181818181M or 31.81818M 

처럼 진수로 변환 그리고 null 허용 진수 변수에 저장하고 싶습니다. decimal formatting without rounding .netStop Rounding In C# At A Certain Number 을 시도했지만 null 가능 십진수는 없습니다. 여기

private decimal? ReturnNullableDecimal(decimal? initValue) 
{ 
     //e.g. initValue = 35M; 
     initValue = 35M; //just to debug; 

     decimal? outputValue = null; 


     if (initValue != null) 
      outputValue = initValue/(decimal)1.10; 
     //now outputValue is 31.818181818181818181818181818M 
     outputValue = Convert.ToDecimal(string.Format("{0:0.0000}", outputValue)); // <- this should be 31.8181 but gives 31.8182 

     return outputValue; 
    } 

사람이 도와 주실 수있는 코드?

+0

a.net에서 뱅커 라운딩이 기본값입니다. 중간 점 라운딩이 필요합니다. –

답변

2

임의의 decimal은 내재적으로 decimal?으로 변환 될 수 있으므로 다른 코드 예에서와 동일한 코드가 작동합니다. 입력 한 내용이 decimal?이라면 거기에서 null을 확인해야합니다. your.namespace.Extensions를 사용 추가; 허용 답변에 따라

private decimal? ReturnNullableDecimal(decimal? initValue) 
{ 
    if (initValue.HasValue) 
     return Math.Truncate(10000 * initValue.Value)/10000; 
    else 
     return null; 
} 
+0

고마워요. 그것은 효과가있다! – Dush

0

나는

namespace your.namespace.Extensions 
{ 
    public static class NullableDecimalExtension 
    { 
     public static decimal? FormatWithNoRoundingDecimalPlaces(this decimal? initValue, int decimalPlaces) 
     { 
      if (decimalPlaces < 0) 
      { 
       throw new ArgumentException("Invalid number. DecimalPlaces must be greater than Zero"); 
      } 

      if (initValue.HasValue) 
       return (decimal?)(Math.Truncate(Math.Pow(10, decimalPlaces) * (double)initValue.Value)/Math.Pow(10, decimalPlaces)); 
      else 
       return null; 
     } 
    } 
} 

사용 확장 기능을 생성 클래스에

호출 방법에서 직접

등을 호출 할 수 있습니다.

initValue = 35M; 
decimal? outputValue = (initValue/(decimal)1.10).FormatWithNoRoundingDecimalPlaces(4); 
//now the outputValue = 31.8181 

소수 자릿수 2 개를 입력해야하는 경우 .FormatWithNoRoundingDecimalPlaces (2);