I have to convert a BigDecimal
value, eg 2.1200
, coming from the database to a string. When I use the toString()
or toPlainString()
of BigDecimal
, it just prints the value 2.12
but not the trailing zeroes.
How do I convert the BigDecimal
to string without losing the trailing zeroes?
try this..
MathContext mc = new MathContext(6); // 6 precision
BigDecimal bigDecimal = new BigDecimal(2.12000, mc);
System.out.println(bigDecimal.toPlainString());//2.12000
To convert a BigDecimal
to a String
with a particular pattern you need to use a DecimalFormat
.
BigDecimal value = .... ;
String pattern = "#0.0000"; // If you like 4 zeros
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
To check the possible values of pattern see here DecimalFormat
double value = 1.25;
// To convet double to bigdecimal
BigDecimal bigDecimalValue = BigDecimal.valueOf(value);
//set 4 trailing value
BigDecimal tempValue = bigDecimalValue.setScale(4, RoundingMode.CEILING);
System.out.println(tempValue.toPlainString());
You can use below code .
BigDecimal d = new BigDecimal("1.200");
System.out.println(d);
System.out.println(String.valueOf(d));
Output is as below :
1.200 1.200
实际上,不要使用 BigDecimal,而是使用 Double 类的 toString()。
Maybe setScale()
will help:
BigDecimal d = new BigDecimal(2.12);
BigDecimal d1 = d.setScale(4)
Then call toPlainString
to get your expected string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.