Several methods of formatting numbers in .NET

xiaoxiao2021-03-06  110

Format Character Description and Association Attributes

C, C currency format. D, D decimal format. e, e scientific count (index) format. f, f fixed point format. g, g is regular format. n, n digital format. R, R round-trip format, ensures that the same value is the same as the original number when converting the digital conversion back to the number. X, x hexadecimal format.

Double Val = Math.pi; console.writeLine (Val.Tostring ()); // Displays 3.14159265358979console.writeline (Val.Tostring ("e")); // Displays 3.141593e 000console.writeline (Val.Tostring "F3"); // displays 3.142int val = 65535; console.writeline (Val.Tostring ("x"))); // Displays fffconsole.writeline (Val.Tostring ("x")); // Displays fffsingle Val = 0.123f; console.writeline (Val.Tostring ("P"))); // DisplayS 12.30% console.writeline (Val.Tostring ("P1")); // DisplayS 12.3% default formatting in numbers and hundred Add a space between the semicolon. The custom method is as follows: where the NumberFormatinfo class is a member of the System.globalization namespace, so the namespace must be imported into the program. Single Val = 0.123f; Object myobj = Numberformatinfo.currentInfo.clone () as NumberFormatInfo; NumberFormatInfo myformat = myobj as NumberFormatInfo; myformat.PercentPositivePattern = 1; Console.WriteLine (val.ToString ( "p", myformat)); // displays 12.30%; Console.WriteLine (val.ToString ( "p1 ", myformat); // displays 12.3%; formatted has great flexibility. The following example demonstrates a meaningful currency structure: Double Val = 1234567.89; int [] groupsize = {2, 1, 3}; Object myobj = Numberformatinfo.currentInfo.clone (); Numberformatinfo My currency = myobj as NumberFormatInfo; mycurrency.CurrencySymbol = "#"; // symbol mycurrency.CurrencyDecimalSeparator = ":"; // decimal mycurrency.CurrencyGroupSeparator = "_"; // separator mycurrency.CurrencyGroupSizes = groupsize; // output # 1_234_5_67: 89console.writeline (Val.Tostring ("C", Mycurrency);

转载请注明原文地址:https://www.9cbs.com/read-101197.html

New Post(0)