C#语言学习代码示例

倦鸟已归时 / 2023-08-16 / 原文

保留数位

namespace BasicGrammarStudy
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(string.Format("{0:F3}", 13.47483327438));  // 13.475
            Console.WriteLine(string.Format("{0:N3}", 13.47483327438));  // 13.475
            Console.WriteLine(string.Format("{0:F}", 13.47483327438));  // 13.47
            Console.WriteLine(13.47483327438.ToString("0.###"));  // 13.475
            Console.WriteLine(Math.Round(13.47483327438, 3));  // 13.475
            Console.WriteLine(Math.Round(13.47483327438, MidpointRounding.AwayFromZero));  // 13
            Console.ReadKey();
        }
    }
}

输出:
13.475
13.475
13.47
13.475
13.475
13

 十六进制数加上一个十进制数然后以十六进制返回结果

{
    class Program
    {
        // 十六进制加十进制
        static string hexAddDec(string hex, int addNum)
        {
            int dec1 = Convert.ToInt32(hex, 16);
            Console.WriteLine(dec1);  // 26
            return string.Format("{0:X}", dec1 + addNum);
        }
        static void Main(string[] args)
        {
            Console.WriteLine(hexAddDec("0x1a", 23));  // 49-->31
            Console.ReadKey();
        }
    }
}