prosource

십진수 값 형식을 선행 공백이 있는 문자열로 지정

probook 2023. 5. 13. 10:19
반응형

십진수 값 형식을 선행 공백이 있는 문자열로 지정

10진수 값을 쉼표/도트 뒤에 한 자리 숫자와 100 미만의 값에 대한 선행 공백을 가진 문자열로 포맷하려면 어떻게 해야 합니까?

예를 들어, 10진수 값은12.3456로 출력되어야 합니다." 12.3"단일 선두 공백으로. 10.011되지요" 10.0".123.123이라"123.1"

표준/사용자 지정 문자열 형식과 함께 작동하는 솔루션을 찾고 있습니다.

decimal value = 12.345456;
Console.Write("{0:magic}", value); // 'magic' would be a fancy pattern.

이 패턴{0,5:###.0}작동해야 함:

string.Format("{0,5:###.0}", 12.3456) //Output  " 12.3"
string.Format("{0,5:###.0}", 10.011)  //Output  " 10.0" 
string.Format("{0,5:###.0}", 123.123) //Output  "123.1"
string.Format("{0,5:###.0}", 1.123)   //Output  "  1.1"
string.Format("{0,5:###.0}", 1234.123)//Output "1234.1"

문자열 보간(C#6+)이 있는 다른 하나:

double x = 123.456;
$"{x,15:N4}"// left pad with spaces to 15 total, numeric with fixed 4 decimals

식 반환:" 123.4560"

value.ToString("N1");

소수점 이하의 숫자를 변경합니다.

편집: 패딩 비트를 놓쳤습니다.

value.ToString("N1").PadLeft(1);

좋은 답변이 많지만, 제가 가장 많이 사용하는 것은 이것입니다(c#6+).

Debug.WriteLine($"{height,6:##0.00}");
//if height is 1.23 =>   "  1.23"
//if height is 0.23 =>   "  0.23"
//if height is 123.23 => "123.23"

위의 모든 솔루션은 반올림하지 않고 솔루션을 찾는 경우를 위해 소수점 반올림을 수행합니다.

decimal dValue = Math.Truncate(1.199999 * 100) / 100;
dValue .ToString("0.00");//output 1.99

문자열을 사용할 때 지역 설정에 따라 "."가 "일 수 있습니다.포맷.

string.Format("{0,5:###.0}", 0.9)     // Output  "   .9"
string.Format("{0,5:##0.0}", 0.9)     // Output  "  0.9"

저는 이것을 사용하게 되었습니다.

string String_SetRPM = $"{Values_SetRPM,5:##0}";
// Prints for example "    0", " 3000", and "24000"

string String_Amps = $"{(Values_Amps * 0.1),5:##0.0}";
// Print for example "  2.3"

정말 고마워.

실제로 0.123인 경우에는 허용된 답이 ".1"을 생성합니다. 이는 예상치 못한 결과일 수 있습니다.

따라서 ###.0 대신 0.0을 숫자 형식으로 사용하는 것이 좋습니다.그러나 필요에 따라 다릅니다(제 의견 하단 참조).

예:

string.Format("{0,5:0.0}", 199.34) // Output "199.3"
string.Format("{0,5:0.0}",  19.34) // Output " 19.3"
string.Format("{0,5:0.0}",   0.34) // Output "  0.3"

{0,5:0.0} 설명

패턴: {{index}, {padding}:{numberFormat}

  • {index}: 문자열에 전달된 매개 변수 목록에서 형식을 지정할 매개 변수의 0 기반 인덱스입니다.형식("format", param0, param1, param2...)
  • {filename}: 패딩할 선행 공간 수
  • {numberFormat}: 번호에 적용할 실제 번호 형식

패딩 설명서: https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros

사용자 지정 번호 형식 설명서: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings

0과 # 소수점 지정자 간의 차이를 비교해 볼 가치가 있습니다.

0 소수점 지정자: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#Specifier0

십진수 지정자: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#SpecifierD

언급URL : https://stackoverflow.com/questions/8293392/format-decimal-value-to-string-with-leading-spaces

반응형