Slide 1
Slide 2
Slide 3

BigDecimal input in java programming (V26)

No Comments

BigDecimal nextBigDecimal()

The nextBigDecimal() method allows reading decimal values with high precision directly from user input as a BigDecimal.

Syntax:

Source Code:

Copied!
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Scanner;

public class Velocity {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter distance (km): ");
        BigDecimal distance = scanner.nextBigDecimal();

        System.out.print("Enter time (hours): ");
        BigDecimal time = scanner.nextBigDecimal();

        // Calculate velocity with 2 decimal places rounding
        BigDecimal velocity = distance.divide(time, 2, RoundingMode.HALF_UP);

        System.out.println("Velocity: " + velocity + " km/h");

        scanner.close();
    }
}

Result:



This line calculates the speed using BigDecimal by dividing the distance by the time, ensuring that the result is accurately rounded.

Watch the video:


Ebook: https://softkhpc.blogspot.com/2025/05/java-programming-ebooks.html

back to top