Math.round用法 .

本文详细解析了Java面试中常见的Math.round函数的使用方法,通过具体代码实例展示了如何进行四舍五入操作。
0人阅读 评论(0) 收藏 编辑 删除

  我们在项目开发中少不了要开发报表,而对于数据的处理,用于不少的函数或是方法是必不可少的。其中就包括四舍五入的方法Math.round,这个的用法也是java面试题中常见的。下面是java代码是Math.round使用方法:

package com.buyli.interview.baseinfo;

 

/**

 * @Copyright @ 2012

 * All right reserved

 * @version 创建时间:Created on 2012-11-22

 * @author 作者:Create by www.360buyli.com

 * @Email: 360buyli@gmail.com

 * @description java面试题中Math.round的用法

 */

 

public class RoundInterview {

         public static void main(String[] args) {

                   System.out.println("Math.round(11.5)输出:"+Math.round(11.5));

                   System.out.println("Math.round(-11.5)输出:"+Math.round(-11.5));

         }

}

所输出的结果是:

Math.round(11.5)输出:12

Math.round(-11.5)输出:-11

JavaJavaScript 等语言中,`Math.floor` 和 `Math.round` 是用于处理浮点数的常用方法。 ### 用法 - **Math.floor**:`Math.floor` 用于向下取整,即返回小于或等于给定数字的最大整数。在 Java 中,方法签名为 `Math.floor(double a)`;在 JavaScript 中可直接使用 `Math.floor(num)` ,其中 `num` 是要处理的数字 [^2][^3]。 - **Math.round**:`Math.round` 用于四舍五入,返回与给定数字最接近的整数。在 Java 中,`Math.round` 有两个重载方法,`Math.round(float a)` 返回 `int` 类型,`Math.round(double a)` 返回 `long` 类型;在 JavaScript 中使用 `Math.round(num)` ,`num` 为要处理的数字 [^2]。 ### 区别 `Math.floor` 总是向下取整,而 `Math.round` 是四舍五入。例如,对于正数,`Math.floor(3.9)` 会返回 3,而 `Math.round(3.9)` 会返回 4;对于负数,`Math.floor(-3.1)` 返回 -4,`Math.round(-3.1)` 返回 -3 [^2][^4]。 ### 示例 #### Java 示例 ```java public class Main { public static void main(String[] args) { double num1 = 3.9; double num2 = -3.1; // Math.floor 示例 System.out.println("Math.floor(3.9): " + Math.floor(num1)); System.out.println("Math.floor(-3.1): " + Math.floor(num2)); // Math.round 示例 System.out.println("Math.round(3.9): " + Math.round(num1)); System.out.println("Math.round(-3.1): " + Math.round(num2)); } } ``` #### JavaScript 示例 ```javascript let num1 = 3.9; let num2 = -3.1; // Math.floor 示例 console.log("Math.floor(3.9): " + Math.floor(num1)); console.log("Math.floor(-3.1): " + Math.floor(num2)); // Math.round 示例 console.log("Math.round(3.9): " + Math.round(num1)); console.log("Math.round(-3.1): " + Math.round(num2)); ``` #### C# 示例 ```csharp using System; class Program { static void Main() { double value = 12.5; // 向下取整 int resultFloor = (int)Math.Floor(value); Console.WriteLine(resultFloor); // 四舍五入 int resultRound = (int)Math.Round(value); Console.WriteLine(resultRound); } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值