- 追加された行はこの色です。
- 削除された行はこの色です。
#author("2020-01-02T21:19:40+09:00","","")
#navi(../)
* 数値を指定した桁数分ゼロで埋めたい [#r599341c]
int(Int32, Integer), decimal(Decimal)のToStringメソッドを使ったゼロパディングのサンプルコードを以下に紹介します。
#htmlinsert(windev-top.html)
#contents
* 関連サイト [#h7713b93]
-[[Microsoft | .NET Int32.ToString メソッド>https://docs.microsoft.com/ja-jp/dotnet/api/system.int32.tostring?view=netframework-4.8#System_Int32_ToString_System_String_]]
* 関連記事 [#r62691b5]
-[[文字列数値を指定した桁数分ゼロで埋めたい・PadLeft>.NET/文字列数値を指定した桁数分ゼロで埋めたい・PadLeft]]
* 動作確認環境 [#lc461e78]
- Windows 10 ver.1909
- Visual Studio 2019
- .NET Core
- コンソールアプリケーション
* ToStringを使った整形 [#c9981856]
使用するメソッドは数値型のToString(string format)を使って整形します。~
System.Int32のToString(string format)は以下のようになっています。(MSサイトからの抜粋)
-指定した書式を使用して、このインスタンスの数値を、それと等価な文字列形式に変換します。~
public string ToString (string format);
-パラメーター~
format String 標準またはカスタムの数値書式指定文字列。
* ToString(string format)のサンプルコード [#t36e8bf0]
以下に ToString(string format)を使った C#, Visual Basic(VB)のサンプルコードを紹介します。~
decimal, int, uint (Decimal, Integer, UInteger)を対象にToString(string format)メソッドを使ってみます。~
尚、サンプルコードでは数値を5桁ゼロパディングします。~
5桁のゼロパディングしたい場合は、0を5つ続けるか、D5のようにDの後に値を設定します。~
decimalでは、D数値のフォーマット指定は例外が発生しました。~
formatについては、以下のインクを参照ください。
-[[Microsoft | .NET 標準の数値形式文字列>https://docs.microsoft.com/ja-jp/dotnet/standard/base-types/standard-numeric-format-strings?view=netframework-4.8]]
** C# [#z2c805ed]
using System;
class Program
{
static void Main(string[] args)
{
decimal pd = 123;
decimal md = -234;
int i = -345;
uint ui = 456;
Console.WriteLine("decimal");
Console.WriteLine("{0} : {1}",pd, pd.ToString("00000"));
Console.WriteLine("{0} : {1}", md, md.ToString("00000"));
Console.WriteLine("int, uint");
Console.WriteLine("{0} : {1}", i, i.ToString("00000"));
Console.WriteLine("{0} : {1}", i, i.ToString("D5"));
Console.WriteLine("{0} : {1}", ui, ui.ToString("00000"));
Console.WriteLine("{0} : {1}", ui, ui.ToString("D5"));
}
}
-実行結果
#ref(01.png)
** Visual Basic(VB) [#a85d2eb1]
Imports System
Module Program
Sub Main(args As String())
Dim pd As Decimal = 123
Dim md As Decimal = -234
Dim i As Integer = -345
Dim ui As UInteger = 456
Console.WriteLine("Decimal")
Console.WriteLine("{0} : {1}", pd, pd.ToString("00000"))
Console.WriteLine("{0} : {1}", md, md.ToString("00000"))
Console.WriteLine("Integer, UInteger")
Console.WriteLine("{0} : {1}", i, i.ToString("00000"))
Console.WriteLine("{0} : {1}", i, i.ToString("D5"))
Console.WriteLine("{0} : {1}", ui, ui.ToString("00000"))
Console.WriteLine("{0} : {1}", ui, ui.ToString("D5"))
End Sub
End Module
-実行結果
#ref(02.png)
以上、System.Int32.ToString(string format), System.Decimal.ToString(format)を使ったゼロパディングのサンプルコードでした。
#htmlinsert(windev-btm.html)