Round Float to 2 Decimal Points in C#

Rounding float in C#: Learn, how to round the given float value to 2 decimal points using C# program? By IncludeHelp Last updated : April 09, 2023

How to Round Float to 2 Decimal Points in C#?

In C#, the simple and easiest way to round a float value to 2 decimal points, we can use a String.Format() function with digits placeholder (#). Pass the custom string to "{0:0.00}" and float number/variable to the function and it prints the float value with 2 decimal points.

Syntax

Use the below syntax to round float to 2 decimal points using String.Format() method:

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

C# program to round float to 2 decimal points

using System;

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      //Only two decimal points
      Console.WriteLine("Two digits after decimal point");
      Console.WriteLine(String.Format("{0:0.00}", 512.4246));
      Console.WriteLine(String.Format("{0:0.00}", 512.4));
      Console.WriteLine(String.Format("{0:0.00}", 512.0));

      Console.WriteLine("\n\nThree digits after decimal point");
      Console.WriteLine(String.Format("{0:0.000}", 512.4246));
      Console.WriteLine(String.Format("{0:0.000}", 512.4));
      Console.WriteLine(String.Format("{0:0.000}", 512.0));

      Console.WriteLine();
    }
  }
}

Output

Two digits after decimal point
512.42
512.40
512.00


Three digits after decimal point
512.425
512.400
512.000



All C#.Net Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.