In C#, you can use the ToString() method with a format specifier to format a decimal number according to a specific pattern. To format a decimal number with two decimal places and omitting trailing zeros, you can use the format string "0.##".

Here's an example:

decimal number = 10.5m;
string formattedNumber = number.ToString("0.##");
Console.WriteLine(formattedNumber);

Output:

10.5

If the decimal number has more than two decimal places, it will be rounded to two decimal places:

decimal number = 10.555m;
string formattedNumber = number.ToString("0.##");
Console.WriteLine(formattedNumber);

Output:

10.56

If the decimal number has fewer than two decimal places, it will still be displayed with two decimal places:

decimal number = 10m;
string formattedNumber = number.ToString("0.##");
Console.WriteLine(formattedNumber);

Output:

10.00

Note that the "0.##" format specifier will only display decimal places if they are significant. If the decimal places are zeroes, they will be omitted

C#decimaltostring0##

原文地址: https://www.cveoy.top/t/topic/iiJx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录