Kotlin 程序将数字舍入到 n 位小数


在本文中,我们将了解如何将数字舍入到 n 位小数。十进制值的舍入是使用 ceil() 或 floor() 函数完成的。

以下是相同内容的演示 -

假设我们的输入是

Input : 3.1415

所需的输出将是 -

Output : 3.2

算法

  • 步骤 1 - 开始

  • 步骤 2 - 声明一个名为 myInput 的浮点值。

  • 步骤 3 - 定义值

  • 步骤 4 - 使用 format() 更改所需的小数位数。存储结果。

  • 步骤 5 - 显示结果

  • 步骤 6 - 停止

示例 1

在此示例中,我们将数字舍入到 n 位小数。首先,让我们为输入声明一个变量

val myInput = 3.1415

现在,我们将使用 %.3f 格式化并舍入输入到 3 位小数 -

println("%.3f".format(myInput))

现在让我们看看将数字舍入到 n 位小数的完整示例 -

fun main() { val myInput = 3.1415 println("The number is defined as $myInput") println("The result after rounding the number to 3 decimal places is: ") println("%.3f".format(myInput)) }

输出

The number is defined as 3.1415
The result after rounding the number to 3 decimal places is: 3.142

示例 2

在此示例中,我们将数字舍入到 n 位小数 -

fun main() { val myInput = 3.1415 println("The number is defined as $myInput") roundDecimal(myInput) } fun roundDecimal(myInput: Double) { println("The result after rounding the number to 3 decimal places is: ") println("%.3f".format(myInput)) }

输出

The number is defined as 3.1415
The result after rounding the number to 3 decimal places is: 3.142

更新于: 2022年10月13日

1K+ 浏览量

开启你的 职业生涯

完成课程获得认证

立即开始
广告

© . All rights reserved.