诉求:项目中有一个 Long 类型的整数,含义是以"分"为单位的价格,需要将其转化为以"元"为单位的字符串,且格式为 “0.00”,即保留 2 位小数,且不丢失精度。
实现过程:Long 转为 double,再用 DecimalFormat 约定格式,将 double 转为 String,代码过程如下所示。
package com.test;
import java.text.DecimalFormat;
public class Test {
public static void main(String[] args) {
// 以“分”为单位的价格,即 1.20 元
Long price = 120L;
double price1 = price.doubleValue() / 100;
System.out.println(price1); // 1.2
// 将结果保留为 0.00 格式
DecimalFormat df = new DecimalFormat("0.00");
String price2 = df.format(price1);
System.out.println(price2); // 1.20
}
}