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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP