You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Freemarker结合openhtmltopdf打印Double值保留两位小数问题

解决Double类型数值打印两位小数的问题

核心原因

Double类型的100.00与100.0在内存中是等价的,默认打印逻辑会省略末尾无意义的零和小数点,因此需要通过格式化语法强制指定输出格式。

常见编程语言实现方案

Python

  • 使用format()函数:
    num = 100.00
    print("{:.2f}".format(num))  # 输出 100.00
    
  • 或者使用f-string(Python 3.6及以上版本):
    num = 100.00
    print(f"{num:.2f}")  # 输出 100.00
    

Java

  • 使用String.format()快速格式化:
    double num = 100.00;
    System.out.println(String.format("%.2f", num));  // 输出 100.00
    
  • 或者使用DecimalFormat类(适合复杂格式化场景):
    import java.text.DecimalFormat;
    
    public class Main {
        public static void main(String[] args) {
            double num = 100.00;
            DecimalFormat df = new DecimalFormat("#.00");
            System.out.println(df.format(num));  // 输出 100.00
        }
    }
    

Swift

  • 使用String(format:)方法:
    let num: Double = 100.00
    print(String(format: "%.2f", num))  // 输出 100.00
    

内容的提问来源于stack exchange,提问作者Mandapati Ganesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 17:15:40