Round Float Before Decimal Point in C#

In this tutorial, we will learn how do you round a float value before decimal point using C# program? By IncludeHelp Last updated : April 09, 2023

How to Round Float Before Decimal Point in C#?

To round a float value before the decimal point, we can use String.Format() function with digits placeholder (#). Pass the custom string to "{0:00.0}" and float number/variable to the function and it prints the float value rounded before the decimal point.

Syntax

Use the below syntax to round float value before decimal point using String.Format() method:

String.Format("{0:00.0}", 2.4567)

C# program to round float value before decimal point

using System;

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      //Minimum two digits before decimal point
      Console.WriteLine("Minimum Two digits before decimal point");
      Console.WriteLine(String.Format("{0:00.0}", 12512.4567));
      Console.WriteLine(String.Format("{0:00.0}", 512.4567));
      Console.WriteLine(String.Format("{0:00.0}", 2.4567));
      Console.WriteLine(String.Format("{0:00.0}", -2.4567));

      //Minimum three digits before decimal point
      Console.WriteLine("Minimum Three digits before decimal point");
      Console.WriteLine(String.Format("{0:000.0}", 12512.4567));
      Console.WriteLine(String.Format("{0:000.0}", 12.4567));
      Console.WriteLine(String.Format("{0:000.0}", 2.4567));
      Console.WriteLine(String.Format("{0:000.0}", -2.4567));

      Console.WriteLine();
    }
  }
}

Output

Minimum Two digits before decimal point
12512.5
512.5
02.5
-02.5
Minimum Three digits before decimal point
12512.5
012.5
002.5
-002.5



All C#.Net Programs

Comments and Discussions!

Load comments ↻





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