Appeal : There is a Long type integer in the project. The meaning is the price in "cents". It needs to be converted into a string with "yuan" as the unit, and the format is "0.00", that is, 2 decimal places are reserved. Without losing accuracy.
Implementation process : Convert Long to double, then use the DecimalFormat convention format to convert double to String. The code process is shown below.
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
}
}