C#

double

Casts

ToString

using System;
class Program
{
static void Main()
{
*// Display percentage of visits that resulted in purchases.*
int purchases = 10;
int visitors = 120;
DisplayPercentage((double)purchases / visitors);
*// Display 50 percent with overloaded method.*
DisplayPercentage(1, 2);
*// Write percentage string of nine tenths.*
Console.WriteLine(GetPercentageString((double)9 / 10));
}
*/// <summary>
/// This method writes the percentage form of a double to the console.
/// </summary>*
static void **DisplayPercentage**(double ratio)
{
string percentage = string.Format(*"Percentage is {0:0.0%}"*, ratio);
Console.WriteLine(percentage);
}
*/// <summary>
/// This method writes the percentage of the top number to the bottom number.
/// </summary>*
static void **DisplayPercentage**(int top, int bottom)
{
DisplayPercentage((double)top / bottom);
}
*/// <summary>
/// This method returns the percentage-formatted string.
/// </summary>*
static string **GetPercentageString**(double ratio)
{
return ratio.ToString(*"0.0%"*);
}
}Percentage is 8.3%
Percentage is 50.0%
90.0%

Divide

Math.Floor

Math.Ceiling

Math.Round

using System;
class Program
{
static void Main()
{
*// We want to have 92.9% from these two numbers.*
int valid = 92;
int total = 99;
*// First multiply top by 100 then divide.*
double percent = (double)(valid * 100) / total; *// <-- Use cast*
*// This is the percent number.*
Console.WriteLine(percent);
Console.WriteLine(Math.Floor(percent));
Console.WriteLine(Math.Ceiling(percent));
Console.WriteLine(Math.Round(percent, 1));
}
}92.9292929292929
92
93
92.9

Modulo

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

This page was last updated on May 30, 2021 (edit).