Write a Java Program to Round a Number to n Decimal Places

Java Program to Round a Number to n Decimal Places

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Round a Number to n Decimal Places
Java Program to Round a Number to n Decimal Places

Write a Java Program to Round a Number to n Decimal Places

PROGRAM: Java Program to Round a Number to n Decimal Places

/*Java Program to Round a Number to n Decimal Places*/

1: Round a Number using format

public class Decimal {

    public static void main(String[] args) {
        double num = 1.34567;

        System.out.format("%.4f", num);
    }
}

2: Round a Number using DecimalFormat

import java.math.RoundingMode;
import java.text.DecimalFormat;

public class Decimal {

    public static void main(String[] args) {
        double num = 1.34567;
        DecimalFormat df = new DecimalFormat("#.###");
        df.setRoundingMode(RoundingMode.CEILING);

        System.out.println(df.format(num));
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *