Change Doubles to BigDecimals
Look at the constructor BigDecimal(String)
double val = 5.2;
BigDecimal bd = new BigDecimal(String.valueOf(val));
System.out.println(bd);
Explore other constructors also of BigDecimal
.
문제
I Have this:
double priceMulti = 1.3;
double price = Double.parseDouble(jTextField1.getText());
//some if's and else's
double date = (1980 * 2);
double random = Math.random()*15;
jLabel28.setText(String.valueOf((priceMulti * price * date * random)/price));
double copies = Double.parseDouble(jLabel28.getText());
jLabel33.setText(String.valueOf(copies / price));
code, and I want to change the variables of price and copies (whose are doubles) to BigDecimals. I Know that there are some topics like those, but my code is a bit different. Solved, thanks!
해결책 2
Change Doubles to BigDecimals
Look at the constructor BigDecimal(String)
double val = 5.2;
BigDecimal bd = new BigDecimal(String.valueOf(val));
System.out.println(bd);
Explore other constructors also of BigDecimal
.
다른 팁
The main thing to avoid is converting your strings to double at any point. Once you do that, the number is rounded to a binary fraction. You can, and should, construct a BigDecimal directly from a String that represents a decimal fraction.
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
String s = "5.2";
double d = 5.2;
BigDecimal fromString = new BigDecimal(s);
BigDecimal fromDouble = new BigDecimal(d);
System.out.println("From string: " + fromString);
System.out.println("From double: " + fromDouble);
}
}
result:
From string: 5.2
From double: 5.20000000000000017763568394002504646778106689453125
fromString
contains the exact conversion of "5.2" to a decimal fraction, ready to do arithmetic. fromDouble has first been rounded to a number that can be exactly represented as a binary fraction. It is very, very close to 5.2, but slightly different.
To construct a BigDecimal representing a compile-time constant, you still need to use the String argument constructor: new BigDecimal("5.2")
not new BigDecimal(5.2)
.