TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Get Percentage From Number With Format String

Handle percentages: get percentages from ratios with format strings.
Percentages. These are often useful in programs. With the numbers 1 and 2, we can get a percentage of 50%. We display and process percentages with doubles.
Notes, methods. With these methods, we solve an annoying rounding problem. Percentages can often be used to improve displayed values for users.Double
First example. We use string.Format to display 2 numbers or ratio as a percentage. The 3 methods all handle percentages. But their logic is implemented in different ways.

Note: DisplayPercentage accepts a double that is a ratio. The {0:0.0%} indicates a percentage with 1 digit past the decimal place.

Note 2: The second DisplayPercentage accepts 2 parameters and then passes the ratio of them to the other method. It casts to double.

Casts

Also: GetPercentageString accepts a double containing a ratio and returns a percentage string using ToString().

ToString
C# program that calculates per cents 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%"); } } Output Percentage is 8.3% Percentage is 50.0% 90.0%
Example 2. Here we convert 2 integers into a percentage manually with division and multiplication. Sometimes you can need raw percentages.

Cast: The double must be assigned to a value cast to double. If you omit the cast, your value will be rounded and probably useless.

Tip: When casting to double, you do not need to surround the entire expression with parentheses.

Divide

Info: Math.Floor rounds down to the nearest integer. Math.Ceiling rounds up to the nearest integer.

Math.FloorMath.CeilingMath.Round
C# program that converts ratios 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)); } } Output 92.9292929292929 92 93 92.9
Modulo. The percentage sign in the C# language has a use as the modulo operator. This forms an expression that will return the remainder of a division of the 2 operands.Modulo

Tip: With modulo division, we can run an operation every N times. This has uses in many programs.

A summary. First we saw how to format ratios as percentages with 3 different methods. Second, we saw how to get a percentage value directly with math, and then round it.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf