Write a Java program to accept a float value of number and return a rounded float value


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

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

  1. import java.util.*;
  2. public class Javamathexcercise {
  3.  
  4. public static void main(String[] args)
  5. {
  6. Scanner in = new Scanner(System.in);
  7. System.out.print("Input any float number: ");
  8. float x = in.nextFloat();
  9. System.out.printf("The rounded value of %f is: %.2f",x, round_num(x));
  10. System.out.printf("\n");
  11. }
  12.  
  13. public static float round_num(float fn)
  14. {
  15. float f_num = (float)Math.floor(fn);
  16. float c_num = (float)Math.ceil(fn);
  17. if ((fn - f_num) > (c_num - fn))
  18. {
  19. return c_num;
  20. }
  21. else if ((c_num - fn) > (fn - f_num))
  22. {
  23. return f_num;
  24. }
  25. else
  26. {
  27. return c_num;
  28. }
  29. }
  30.  
  31. }

Result

java techstudy.org

     





Related Topics




Popular Posts