Write a Java program to round a float number to specified decimals


Introduction

In this demo I have used NetBeans IDE 8.2 for debugging purpose. But you can use any java programming language compiler as per your availability..


techstudy.org

Kindle Paperwhite High Resolution Display Tablet | Rs. 9999

  1. import java.lang.*;
  2. import java.math.BigDecimal;
  3. public class Javamathexcercise {
  4. public static void main(String[] args) {
  5. float num = 1541.3256412f;
  6. int decimal_place = 4;
  7. BigDecimal bd_num = new BigDecimal(Float.toString(num));
  8. bd_num = bd_num.setScale(decimal_place, BigDecimal.ROUND_HALF_UP);
  9. System.out.printf("Original number: %.7f\n",num);
  10. System.out.println("Rounded upto 4 decimal: "+bd_num);
  11. }
  12. }

Result

java techstudy.org

     





Related Topics


Responses




Popular Posts

Facebook

Founded in 2016, Tech Study passionately delivers stylish and dynamic innovative information to programmer and technology lovers. http://www.techstudy.org/.