Created
February 12, 2013 22:29
-
-
Save yetanotherchris/4774077 to your computer and use it in GitHub Desktop.
Rounding with number formatting in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// No number specifier | |
Console.WriteLine("a) {0}", numSingle); | |
// Round up, ignore any decimal points. | |
Console.WriteLine("a) {0:##}", numSingle); | |
// Round up to 1 dp. | |
Console.WriteLine("b) {0:.#}", numSingle); | |
// Round up to 2 dp. | |
Console.WriteLine("c) {0:.##}", numSingle); | |
// Round up to 3 dp. | |
Console.WriteLine("d) {0:.###}", numSingle); | |
// Floats work up to 7 digits, then any extra digit after the decimal place is rounded up, or ignored. | |
// So 4 decimal places is the maximum a number up to 1000 can store, e.g. 999.1234. | |
// It's recommended to always use double (Double) or decimal (Decimal) for applications involving currencies. | |
double numDouble = 1000000.5664; | |
float numSingle2 = 999.9999f; | |
Console.WriteLine("e) {0:.####}", numDouble); | |
Console.WriteLine("e2) {0:.####}", numSingle2); | |
Console.WriteLine("e3) {0:##}", numSingle2); | |
Output: | |
a) 10.566 | |
a) 11 | |
b) 10.6 | |
c) 10.57 | |
d) 10.566 | |
e) 1000000.5664 | |
e2) 999.9999 | |
e3) 1000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment