Math.Round()函数说明

Math.Round()并不是严格意义上的是四舍五入函数。它默认的执行的是“银行家舍入”算法,即四舍六入五取偶。概括为:四舍六入五考虑、五后非零就进一,五后皆零看奇偶,五前为偶应舍去、五前为奇要进一

        当为5时,取离着最近的偶数。见下图:

               

测试代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MathRoundTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Math.Round(1234.5).ToString());  //输出:1234
            Console.WriteLine(Math.Round(1234.50).ToString());  //输出:1234
            Console.WriteLine(Math.Ro

在不同编程语言中,`Math.round()` 函数通常用于将一个数字四舍五入为最接近的整数。 在 JavaScript 里,`Math.round()` 是内置的全局函数,功能是把一个数字四舍五入为最接近的整数,它直接作为全局函数调用,返回最接近的整数值。与之相对,`round()` 是 `Number` 对象的方法,二者调用方式不同,但功能都是四舍五入取整 [^1]。 在 Java 中,`Math.round()` 函数根据传入参数类型返回不同类型的结果。若传入 `float` 型参数,返回 `int` 型值;若传入 `double` 型参数,返回 `long` 型值 [^2]。 以 Java 代码示例说明其具体表现: ```java public class TestMathRound { public static void main(String[] args) { System.out.println("小数点后第一位=5"); System.out.println("正数:Math.round(11.5)=" + Math.round(11.5));//12 System.out.println("负数:Math.round(-11.5)=" + Math.round(-11.5));//-11 System.out.println(); System.out.println("小数点后第一位<5"); System.out.println("正数:Math.round(11.46)=" + Math.round(11.46));//11 System.out.println("负数:Math.round(-11.46)=" + Math.round(-11.46));//-11 System.out.println(); System.out.println("小数点后第一位>5"); System.out.println("正数:Math.round(11.68)=" + Math.round(11.68));//12 System.out.println("负数:Math.round(-11.68)=" + Math.round(-11.68));//-12 } } ``` 从上述代码可以看出,当小数点后第一位是 5 时,正数向上取整,负数向下取整;当小数点后第一位小于 5 时,直接舍去小数部分;当小数点后第一位大于 5 时,向上取整 [^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值