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.