Java 程序将一个数字四舍五入到 n 个小数位
在本文中,我们将了解如何将数字四舍五入到 n 个小数位。十进制值的四舍五入使用 CEIL 或 FLOOR 函数完成。
以下是其演示 −
输入
假设我们的输入是 −
Input : 3.1415
输出
所需的输出将是 −
Output : 3.2
算法
Step 1 - START Step 2 - Declare a float variable values namely my_input. Step 3 - Read the required values from the user/ define the values Step 4 – Use the CEIL function to round the number to the required decimal places. In this example we are rounding up to 2 decimal places. Store the result. Step 5- Display the result Step 6- Stop
示例 1
在此,输入是由用户根据提示输入的。您可以在我们的 编码基础工具
中实时尝试此示例。
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;
public class DecimalFormatting {
public static void main(String[] args) {
float my_input;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A scanner object has been defined ");
System.out.print("Enter the first binary number : ");
my_input = my_scanner.nextFloat();
DecimalFormat roundup_decimal = new DecimalFormat("#.#");
roundup_decimal.setRoundingMode(RoundingMode.CEILING);
System.out.println("The rounded up value of " +my_input + " is ");
System.out.println(roundup_decimal.format(my_input));
}
}输出
Required packages have been imported A scanner object has been defined Enter the first binary number : 3.1415 The decimal number is defined as 3.1415 The rounded up value of 3.1415 is 3.2
示例 2
在此,整数已预先定义,并访问其值并显示在控制台上。
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class DecimalFormatting {
public static void main(String[] args) {
System.out.println("Required packages have been imported");
double my_input = 3.1415;
System.out.println("The decimal number is defined as " +my_input);
DecimalFormat roundup_decimal = new DecimalFormat("#.#");
roundup_decimal.setRoundingMode(RoundingMode.CEILING);
System.out.println("The rounded up value of " +my_input + " is ");
System.out.println(roundup_decimal.format(my_input));
}
}输出
Required packages have been imported The decimal number is defined as 3.1415 The rounded up value of 3.1415 is 3.2
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP