C# で float を小数点以下 2 桁に丸める
この投稿では、C# で float を小数点以下 2 桁に丸める方法について説明します。
1.使用する ToString()
方法
使用できます ToString()
浮動小数点値を小数点以下の桁数にフォーマットするメソッド。の ToString()
メソッドは数値フォーマット文字列を受け入れ、現在のインスタンス値を同等の文字列に変換します。 float を小数点以下 2 桁に制限するには、 #.##
以下に示すように、フォーマット指定子:
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { float f = 3.14285f; string s = f.ToString("#.##"); Console.WriteLine(s); // 3.14 } } |
C# は、浮動小数点値を小数点以下 2 桁に丸めるために使用できるいくつかの標準フォーマット指定子を提供します。これらについては、以下で説明します。
1. 「0」カスタム書式指定子.
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { float f = 3.14285f; string s = f.ToString("0.00"); Console.WriteLine(s); // 3.14 } } |
1 2 3 4 5 6 7 8 9 10 11 12 |
using System; public class Example { public static void Main() { float f = 3.14285f; string s = f.ToString("F2"); Console.WriteLine(s); // 3.14 } } |
3. 数値書式指定子 (N) グループ区切り付き
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { float f1 = 3.14285f; Console.WriteLine(f1.ToString("N2")); // 3.14 float f2 = 10000.874287f; Console.WriteLine(f2.ToString("N2")); // 10,000.87 } } |
2.使用する Decimal.Round()
方法
別の一般的なアプローチは、 Decimal.Round()
指定された小数点以下の桁数に値を丸める方法。この方法を使用する利点は、値が次のように保持されることです。 Decimal
、文字列を返す代わりに。次の例で説明します。
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { decimal d = 3.14285m; d = Decimal.Round(d, 2); Console.WriteLine(d); // 3.14 } } |
を使用して、10 進数を丸める方法を指定することもできます。 MidpointRounding
列挙型。たとえば、次のコードは次の丸め規則を使用します。 MidpointRounding.AwayFromZero
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using System; public class Example { public static void Main() { decimal d1 = 3.505m; d1 = Decimal.Round(d1, 2); Console.WriteLine(d1); // 3.50 decimal d2 = 3.505m; d2 = Decimal.Round(d2, 2, MidpointRounding.AwayFromZero); Console.WriteLine(d2); // 3.51 } } |
The Math
クラスはまた提供します Round()
指定された小数桁数に値を丸める方法。次の例では、さまざまな入力で出力を提供します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; public class Example { public static void Main() { float f1 = 3.14285f; double d1 = Math.Round(f1, 2); Console.WriteLine(d1); // 3.14 float f2 = 3.1000f; double d2 = Math.Round(f2, 2); Console.WriteLine(d2); // 3.1 float f3 = 3.0000f; double d3 = Math.Round(f3, 2); Console.WriteLine(d3); // 3 } } |
3.使用する String.Format()
方法
に似ています ToString()
メソッド、あなたは使用することができます String.Format()
浮動小数点値を小数点以下 2 桁に丸める方法。次の例は、 #.##
フォーマット指定子、 0
カスタム書式指定子、固定小数点書式指定子 (F)
、および数値書式指定子 (N)
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; public class Example { public static void Main() { float f = 3.14285f; string s = String.Format("{0:0.00}", f); Console.WriteLine(s); // 3.14 s = String.Format("{0:#.##}", f); Console.WriteLine(s); // 3.14 s = String.Format("{0:F2}", f); Console.WriteLine(s); // 3.14 s = String.Format("{0:N2}", f); Console.WriteLine(s); // 3.14 } } |
これで、C# で float を小数点以下 2 桁に丸めることができました。