将一个浮点类型的小数,按照四舍五入保留两位小数

1、DecimalFormat格式化数字

 1 import java.text.DecimalFormat;
 2 import java.util.Scanner;
 3 
 4 /**
 5  *
 6  * 功能描述: 练习Lianxi06四舍五入
 7  *
 8  *
 9  * @ Author: apple.
10  * @ Date: 2019/11/22 7:56 PM
11 */
12 public class LianXi07 {
13 
14     private static Scanner sc = new Scanner(System.in);
15         /*DecimalFormat格式化数字*/
16     public static void main(String[] args) {
17         System.out.println("输入一个数:");
18         double num = sc.nextDouble();
19         //          创建DecimalFormat对象
20         DecimalFormat df = new DecimalFormat("#.00");
21         String sum = df.format(num);//     调用df.format(num1)方法,传入参数 sum 接收值
22         System.out.println("四舍五入保留两位小数后:num="+sum);
23     }
24 }

 运行结果:

DecimalFormat("#.00")方法中,"#.00"为设置数字格式,# 表示只要有可能就把数字拉上这个位置。小数点后有两位数字,有几个0表示小数点后保留几位小数,不足用0补齐,如上程序,输入num1为2.5,设置保留两位小数,不够0补齐,所以输出num=2.50。

2、字符串格式化-String.format()的使用

 String类的format()方法用于创建格式化的字符串以及连接多个字符串对象

 1     private static Scanner sc = new Scanner(System.in);
 2     public static void main(String[] args) {
 3         System.out.println("请输入一个小数:");
 4         //hasNextDouble()判断是否输入的数是数字。
 5         while (!sc.hasNextDouble()){
 6             System.out.println("输入有误请重输:");
 7             sc.next();
 8         }
 9         double num = sc.nextDouble();
10         //          调用df.format(num1)方法,传入参数
11     System.out.println(String.format("四舍五入保留两位小数后:num="+"%.2f",num));

运行结果:

format()方法中的两个参数,format("%.2f", num2),例子中的第一个参数为数字格式,百分号表示小数点前的整数部分,“.”表示小数点,数字2表示保留小数位的个数,不足用0补齐,如上程序。“f”表示浮点类型,第二个参数为传入需要更改格式的参数。

原文地址:https://www.cnblogs.com/appleworld/p/11914094.html