[펌] c# String.Format && string 자릿수 맞추기
String Format for Int [C#]
Integer numbers can be formatted in .NET in many ways. You can use static method String.Format or instance method int.ToString. Following examples shows how to align numbers (with spaces or zeroes), how to format negative numbers or how to do custom formatting like phone numbers.
Add zeroes before number
To add zeroes before a number, use colon separator „:“and write as many zeroes as you want.
[C#]
String.Format("{0:00000}", 15); // "00015"
String.Format("{0:00000}", -15); // "-00015"
Align number to the right or left
To align number to the right, use comma „,“ followed by a number of characters. This alignment option must be before the colon separator.
[C#]
String.Format("{0,5}", 15); // " 15"
String.Format("{0,-5}", 15); // "15 "
String.Format("{0,5:000}", 15); // " 015"
String.Format("{0,-5:000}", 15); // "015 "
Different formatting for negative numbers and zero
You can have special format for negative numbers and zero. Usesemicolon separator „;“ to separate formatting to two or three sections. The second section is format for negative numbers, the third section is for zero.
[C#]
String.Format("{0:#;minus #}", 15); // "15"
String.Format("{0:#;minus #}", -15); // "minus 15"
String.Format("{0:#;minus #;zero}", 0); // "zero"
Custom number formatting (e.g. phone number)
Numbers can be formatted also to any custom format, e.g. like phone numbers or serial numbers.
[C#]
String.Format("{0:+### ### ### ###}", 447900123456); // "+447 900 123 456"
String.Format("{0:##-####-####}", 8958712551); // "89-5871-2551"
출처 http://www.csharp-examples.net/examples/
'Programming > C#' 카테고리의 다른 글
[Exception] ArgumentOutOfRangeException: Year, Month, and Day parameters describe an un-representable DateTime. (0) | 2024.02.29 |
---|---|
[링크] C# 특정 문자열 삭제, 특정 문자열 교체 Regex.Replace (0) | 2023.11.08 |
[링크] [C#][.NET framework] Directory.GetFiles() 로 여러 확장자 필터링 하기 (0) | 2023.02.21 |
[링크] [C#/.Net][String To DateTime] 문자형을 Datetime형으로 변경하기 (0) | 2022.10.06 |
[링크][C# 문법] C# 문자열에서 공백(띄어쓰기) 체크(확인) 하는 방법 (0) | 2022.09.05 |