how to convert a number into a decimal number in java

how to convert a number into a decimal number in java

To convert a number into a decimal number in Java, you can use the BigDecimal class, which represents an arbitrary-precision decimal number.

Here is an example of how you can use the BigDecimal class to convert a number to a decimal number:

re‮f‬er to:lautturi.com
int x = 123;
BigDecimal decimal = new BigDecimal(x);

This code assigns the integer 123 to the variable x, and then creates a BigDecimal object from the integer using the BigDecimal constructor. The result is stored in the decimal variable.

You can also use the BigDecimal class to convert a string representation of a number to a decimal number, like this:

String s = "123.45";
BigDecimal decimal = new BigDecimal(s);

This code assigns the string "123.45" to the variable s, and then creates a BigDecimal object from the string using the BigDecimal constructor. The result is stored in the decimal variable.

The BigDecimal class provides various methods for performing arithmetic and other operations on decimal numbers, such as addition, subtraction, multiplication, division, and so on. You can use these methods to manipulate and format the decimal numbers as needed.

Note that the BigDecimal class is immutable, which means that its value cannot be changed after it is created. If you need to modify a BigDecimal object, you will need to create a new object with the modified value.

Created Time:2017-11-01 12:05:14  Author:lautturi