文章目录
- 前言
- 1. Decimal 的基本特性
- 2. 基本用法示例
- 3. 特殊值与转换
- 4. 数学运算示例
- 5. 精度处理示例
- 6. 比较操作示例
- 7. 货币计算示例
- 8. Decimal 的保留小数位数
- 9. 处理 Decimal 的溢出和下溢
- 10. 避免浮点数计算误差
- 总结
前言
  decimal 是 C# 中一种用于表示高精度十进制数的关键字。它主要用于金融和其他需要精确计算的场景,因其能够减少因浮点数运算产生的误差。decimal 类型能够表示的数值范围较大,并且保持精度,适合需要精确表示的场合。
 
1. Decimal 的基本特性
大小和范围: decimal 类型占用 128 位(16 字节),其有效位数为 28-29 位数字,能够表示的数值范围为 -79,228,162,514,264,337,593,543,950,335 到 79,228,162,514,264,337,593,543,950,335。
 精度: decimal 类型是一个高精度的数据类型,适合用来表示金融货币的数值,能够尽量避免因舍入错误而导致的财务问题。
 运算: decimal 类型支持加、减、乘、除等基本运算。
2. 基本用法示例
using System;
class Program
{
    static void Main()
    {
        // 声明 decimal 变量
        decimal price = 19.99m; // 使用 'm' 后缀来表示 decimal 类型
        decimal quantity = 3;
        decimal totalCost = price * quantity;
        Console.WriteLine($"每个价格: {price}, 数量: {quantity}, 总费用: {totalCost}");
    }
}
3. 特殊值与转换
可以通过 Convert 类将其他数据类型转换为 decimal 类型,也可以通过格式化的方式进行输出。使用 decimal 时,通常要注意转换时可能出现的精度问题。
using System;
class Program
{
    static void Main()
    {
        // 从其他类型转换
        double d = 10.5;
        decimal decValue = Convert.ToDecimal(d);
        Console.WriteLine($"转换后的 decimal 值: {decValue}");
        // 显示格式化
        decimal amount = 123456.789m;
        Console.WriteLine($"格式化金额: {amount:C}"); // C 表示货币格式
    }
}
4. 数学运算示例
decimal 支持多种数学运算,以下示例展示了加减乘除操作及结果的精确性。
using System;
class Program
{
    static void Main()
    {
        decimal a = 10.5m;
        decimal b = 3.3m;
        decimal addResult = a + b;
        decimal subResult = a - b;
        decimal mulResult = a * b;
        decimal divResult = a / b;
        Console.WriteLine($"加法结果: {addResult}");
        Console.WriteLine($"减法结果: {subResult}");
        Console.WriteLine($"乘法结果: {mulResult}");
        Console.WriteLine($"除法结果: {divResult}");
    }
}
5. 精度处理示例
当处理涉及多个 decimal 运算时,您可能会需要控制小数位数,使用 Math.Round 方法可实现这一点。
using System;
class Program
{
    static void Main()
    {
        decimal value = 1.23456789m;
        // 保留两位小数
        decimal roundedValue = Math.Round(value, 2);
        Console.WriteLine($"原始值: {value}, 四舍五入后的值: {roundedValue}");
    }
}
6. 比较操作示例
decimal 可以用于比较和排序操作,以下示例展示了如何比较两个 decimal 数值。
using System;
class Program
{
    static void Main()
    {
        decimal a = 100.25m;
        decimal b = 100.25m;
        decimal c = 200.50m;
        Console.WriteLine($"a == b: {a == b}");
        Console.WriteLine($"a < c: {a < c}");
        Console.WriteLine($"a > c: {a > c}");
    }
}
7. 货币计算示例
在实际应用中,decimal 类型常常用于货币计算。以下示例演示了购物车中的商品总价计算。
using System;
using System.Collections.Generic;
class Program
{
    public class Product
    {
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int Quantity { get; set; }
    }
    static void Main()
    {
        List<Product> cart = new List<Product>
        {
            new Product { Name = "图书", Price = 39.99m, Quantity = 2 },
            new Product { Name = "鼠标", Price = 29.99m, Quantity = 1 }
        };
        decimal totalAmount = 0;
        foreach (var product in cart)
        {
            totalAmount += product.Price * product.Quantity;
        }
        Console.WriteLine($"购物车总金额: {totalAmount:C}"); // 使用货币格式
    }
}
8. Decimal 的保留小数位数
在某些情况下,需要将 decimal 保留固定的小数位数。可以借助 Math.Round 来实现。
using System;
class Program
{
    static void Main()
    {
        decimal value = 123.456789m;
        // 保留 3 位小数
        decimal result = Math.Round(value, 3);
        Console.WriteLine($"保留三位小数: {result}"); // 输出: 123.457
    }
}
9. 处理 Decimal 的溢出和下溢
在数学计算中,避免溢出和下溢是非常重要的。可以使用 try-catch 处理计算时的异常情况。
using System;
class Program
{
    static void Main()
    {
        try
        {
            decimal largeValue = decimal.MaxValue;
            decimal result = largeValue + 1; // 可能溢出
            Console.WriteLine($"计算结果: {result}");
        }
        catch (OverflowException ex)
        {
            Console.WriteLine($"发生溢出: {ex.Message}");
        }
    }
}
10. 避免浮点数计算误差
使用 decimal 可以避免常见的浮点数计算误差,例如,以下示例展示了一个浮点数计算的不准确性。
using System;
class Program
{
    static void Main()
    {
        float floatValue = 0.1f + 0.2f;
        Console.WriteLine($"浮点数计算: {floatValue}"); // 输出: 0.300000012
        decimal decimalValue = 0.1m + 0.2m;
        Console.WriteLine($"十进制计算: {decimalValue}"); // 输出: 0.3
    }
}
总结
  decimal 是 C# 中一个非常优秀的数值类型,特别适用于需要高精度和准确性的场景,如金融计算。
 






![第二部分:基础知识 6.函数 --[JavaScript 新手村:开启编程之旅的第一步]](https://i-blog.csdnimg.cn/direct/471ee50bacee49c4a7c64573fa3c7975.png#pic_center)












