- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Kotlin Program to Round a Number to n Decimal Places
In this article, we will understand how to round a number to n decimal places. Rounding of decimal values are done using the ceil() or floor() functions.
Below is a demonstration of the same −
Suppose our input is
Input : 3.1415
The desired output would be −
Output : 3.2
Algorithm
Step 1 − START
Step 2 − Declare a float value namely myInput.
Step 3 − Define the values
Step 4 − Use format() to alter the number of decimal places required. Store the result.
Step 5 − Display the result
Step 6 − Stop
Example 1
In this example, we will Round a Number to n Decimal Places. First, let us declare a variable for input
val myInput = 3.1415
Now, we will format and round the input to 3 decimal places using %.3f −
println("%.3f".format(myInput))
Let us now see the complete example to round a number to n decimal places −
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)) }
Output
The number is defined as 3.1415 The result after rounding the number to 3 decimal places is: 3.142
Example 2
In this example, we will round a Number to n Decimal Places −
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)) }
Output
The number is defined as 3.1415 The result after rounding the number to 3 decimal places is: 3.142