I am creating a Currency converter using BigDecimal and now I am suck with an issue.
I have a user-defined number - "Amount" (this is the amount of currency you want to convert)
I am putting that userValue through the scanner class but I have only ever done this successfully with the following :
int userInput = new scanner.nextint();
I would have loved userinput to be passed as a BigDecimal
but my understanding of java is very limited.
would you suggest converting the double to BigDecimal or is there a much simple way.
CodePudding user response:
If you would like to get user input as a BigDecimal
then you can use one of Scanner
class method nextBigDecimal()
To convert existing double
to BigDecimal
you can use BigDecimal.valueOf()
method.
Code sample:
public static void main(String[] args) {
var scanner = new Scanner(System.in);
System.out.println("Enter BigDecimal");
var number = scanner.nextBigDecimal();
System.out.println("BigDecimal from user input: " number);
var doubleNumber = 2.15;
var decimal = BigDecimal.valueOf(doubleNumber);
System.out.println("Double converted to BigDecimal: " decimal);
}
Listing:
Enter BigDecimal
2,15
BigDecimal from user input: 2.15
Double converted to BigDecimal: 2.15
Process finished with exit code 0
Keep in mind that while converting double
to BigDecimal
you may loose some accuracy of data, because double
is less accurate comparing to BigDecimal
.
CodePudding user response:
You can use nextBigInteger
:
Scanner sc = new Scanner(System.in);
BigInteger userInput = sc.nextBigInteger();