- 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
Java Program to save decimal
Let’s say the value is 0.10705921712947473 and you want to save only the first 3 decimal digits. At first let us declare the values −
double val = 320.0 / 2989.0; BigDecimal big = new BigDecimal(val);
Now, use setScale() and set the parameter as 3 to save 3 decimal places −
big = big.setScale(3, RoundingMode.HALF_DOWN);
Example
import java.math.BigDecimal; import java.math.RoundingMode; public class Demo { public static void main(String[] args) { double val = 320.0 / 2989.0; BigDecimal big = new BigDecimal(val); System.out.println(String.format("Value = %s", val)); // scale big = big.setScale(3, RoundingMode.HALF_DOWN); double val2 = big.doubleValue(); System.out.println(String.format("Scaled result = %s", val2)); } }
Output
Value = 0.10705921712947473 Scaled result = 0.107
Advertisements