Math 四舍五入数字计算

本文详细介绍了如何使用C#的decimal类型进行小数保留和四舍五入操作,包括Math.Round、Math.Floor、Math.Truncate函数的用法,并展示了不四舍五入情况下保留指定位数的技巧。
摘要由CSDN通过智能技术生成

保留小数位【推荐

/// <summary>
/// 保留小数
/// </summary>
/// <param name="number">数值</param>
/// <param name="digit">保留小数位长度</param>
/// <param name="round">是否四舍五入</param>
/// <returns></returns>
private decimal SetDecimal(decimal number, int digit = 2, bool round = false)
{
    decimal result = 0M;
    if (round)
    {
        result = Math.Round(number, digit);
    }
    else
    {
        string length = "1";
        for (int i = 0; i < digit; i++)
        {
            length += "0";
        }
        int multiple = Convert.ToInt32(length);
        result = Math.Truncate(number * multiple) / multiple;
        //result = Math.Floor(number * multiple) / multiple;
    }
    return result;
}

[HttpGet]
public IActionResult GetRetainDecimals(decimal number = 100.12678M, int digit = 2, bool round = false)
{
    var result = SetDecimal(number, digit, round);
    return Ok(result);
}

四舍五入,取整

Math.Round(Convert.ToDouble(100.99), 0)

四舍五入,保留2位小数

100.99789.ToString("f2");

不四舍五入,保留2位小数

Math.Floor(Convert.ToDouble(100.99789) * 100) / 100.00;

Math.Truncate(1.3278 * 100) / 100;

向上取整,不四舍五入

Math.Ceiling(1.0);
Math.Ceiling(1.1);
Math.Ceiling(1.5);
Math.Ceiling(3.1);

向下取整,不四舍五入

Math.Floor(1.0);
Math.Floor(1.1);
Math.Floor(1.5);
Math.Floor(1.9);

绝对值

Math.Abs(-1)

计算指定数字的平方根

Math.Sqrt(9)

*
*
*
*
*

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值