Java 程序将数字四舍五入到小数点后 n 位
javaobject oriented programmingprogramming更新于 2024/4/13 20:28:17
在本文中,我们将了解如何将数字四舍五入到小数点后 n 位。使用 CEIL 或 FLOOR 函数对小数值进行四舍五入。
下面是相同的演示 −
输入
假设我们的输入是 −
输入:3.1415
输出
所需的输出将是 −
输出:3.2
算法
步骤 1 - 开始 步骤 2 - 声明一个浮点变量值,即 my_input。 步骤 3 - 从用户处读取所需值/定义值 步骤 4 - 使用 CEIL 函数将数字四舍五入到所需的小数位。在此示例中,我们将四舍五入到小数点后 2 位。存储结果。 步骤 5 - 显示结果 步骤 6 - 停止
示例 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
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

