[C#] 부동 소수점을 소수점 2 자리로 서식 지정

현재 고객 웹 사이트를위한 판매 모듈을 구축 중입니다. 지금까지 완벽하게 계산할 판매가를 얻었지만 결과는 소수점 이하 두 자리로 서식을 지정하는 것입니다.

현재 변수를 호출하여 결과를 목록보기에 바인딩 할 수 있습니다.

Sale = float.Parse(((x.Sale_Price - (x.Sale_Price * (x.Discount_Price / 100))).ToString())),

누구나 소수점 이하 2 자리로 출력 형식을 지정하는 방법을 보여 줄 수 있습니까 ?? 많은 감사합니다!



답변

형식을 ToString메소드 에 전달할 수 있습니다 ( 예 :

myFloatVariable.ToString("0.00"); //2dp Number

myFloatVariable.ToString("n2"); // 2dp Number

myFloatVariable.ToString("c2"); // 2dp currency

표준 숫자 형식 문자열


답변

가장 먼저해야 할 일은 가격 decimal대신 유형을 사용하는 것입니다 float. float대부분의 소수를 정확하게 표현할 수 없기 때문에 사용하는 것은 절대 허용되지 않습니다.

일단 완료하면 Decimal.Round()2 자리로 반올림하는 데 사용할 수 있습니다.


답변

String.Format("{0:#,###.##}", value)

C #의 문자열 형식화에서 보다 복잡한 예 :

String.Format("{0:$#,##0.00;($#,##0.00);Zero}", value);

1243.50을 통과하면“$ 1,240.00 ″이 출력됩니다. 숫자가 음수이면 동일한 형식이지만 괄호 안에 표시되고 숫자가 0이면 문자열 “Zero”가 출력됩니다.


답변

나는 믿는다:

String.Format("{0:0.00}",Sale);

해야합니다.

링크 문자열 형식 예 참조
C #


답변

string outString= number.ToString("####0.00");


답변

이미 언급했듯이 형식화 된 결과를 사용해야합니다. 이는 모든 통해 이루어집니다 Write(), WriteLine(), Format(), 및 ToString()방법.

언급되지 않은 것은 지정된 소수점 이하 자릿수를 허용 하는 고정 소수점 형식 입니다. ‘F’를 사용하고 ‘F’뒤에 오는 숫자는 예제에 표시된 것처럼 출력 된 소수 자릿수입니다.

Console.WriteLine("{0:F2}", 12);    // 12.00 - two decimal places
Console.WriteLine("{0:F0}", 12.3);  // 12 - ommiting fractions


답변

보간 된 문자열 을 사용하려는 경우입니다 . 나는 시행 착오에 지쳐서 스칼라를 포맷해야 할 때마다 수많은 문서를 스크롤하기 때문에 실제로 이것을 게시하고 있습니다.

$"{1234.5678:0.00}"        "1234.57"        2 decimal places, notice that value is rounded
$"{1234.5678,10:0.00}"     "   1234.57"     right-aligned
$"{1234.5678,-10:0.00}"    "1234.57   "     left-aligned
$"{1234.5678:0.#####}"     "1234.5678"      5 optional digits after the decimal point
$"{1234.5678:0.00000}"     "1234.56780"     5 forced digits AFTER the decimal point, notice the trailing zero
$"{1234.5678:00000.00}"    "01234.57"       5 forced digits BEFORE the decimal point, notice the leading zero
$"{1234.5612:0}"           "1235"           as integer, notice that value is rounded
$"{1234.5678:F2}"          "1234.57"        standard fixed-point
$"{1234.5678:F5}"          "1234.56780"     5 digits after the decimal point, notice the trailing zero
$"{1234.5678:g2}"          "1.2e+03"        standard general with 2 meaningful digits, notice "e"
$"{1234.5678:G2}"          "1.2E+03"        standard general with 2 meaningful digits, notice "E"
$"{1234.5678:G3}"          "1.23E+03"       standard general with 3 meaningful digits
$"{1234.5678:G5}"          "1234.6"         standard general with 5 meaningful digits
$"{1234.5678:e2}"          "1.23e+003"      standard exponential with 2 digits after the decimal point, notice "e"
$"{1234.5678:E3}"          "1.235E+003"     standard exponential with 3 digits after the decimal point, notice "E"
$"{1234.5678:N2}"          "1,234.57"       standard numeric, notice the comma
$"{1234.5678:C2}"          "$1,234.57"      standard currency, notice the dollar sign
$"{1234.5678:P2}"          "123,456.78 %"   standard percent, notice that value is multiplied by 100
$"{1234.5678:2}"           "2"              :)

성능 경고

보간 된 문자열이 느립니다. 내 경험상 이것은 순서입니다 (빠른 속도).

  1. value.ToString(format)+" blah blah"
  2. string.Format("{0:format} blah blah", value)
  3. $"{value:format} blah blah"