V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
rqxiao
V2EX  ›  Java

Java 里有什么可以把一个 BigDecimal 转成这样的格式

  •  
  •   rqxiao · 2020-08-20 13:13:29 +08:00 · 2149 次点击
    这是一个创建于 1317 天前的主题,其中的信息可能已经有所发展或是发生改变。

    交易金额,单位为分,左补 0 至补齐 12 位,例如 000000000001 表示 1 分,000000000100 表示 1 元。

    9 条回复    2020-08-20 19:39:28 +08:00
    selca
        1
    selca  
       2020-08-20 13:43:37 +08:00
    转成 String 想怎么搞怎么搞
    k9990009
        2
    k9990009  
       2020-08-20 13:47:55 +08:00
    自己处理,返回的是 json 的话,重写 BigDecimal 的序列化方法就是了
    passerbytiny
        3
    passerbytiny  
       2020-08-20 13:49:13 +08:00 via Android
    不管原数据是啥类型,补零(或者任何格式化)后就变成 String 类型了,所以格式化自觉交给 String 体系去处理,BigDecimal 及任何数字类型都不用理会。
    crystom
        4
    crystom  
       2020-08-20 13:53:40 +08:00
    java 程序员也想要 leftpad [doge]
    chendy
        5
    chendy  
       2020-08-20 13:58:52 +08:00   ❤️ 3
    ```java
    DecimalFormat format = new DecimalFormat("000000000000");
    BigDecimal bigDecimal = new BigDecimal(100L);
    System.out.println(format.format(bigDecimal)); // 000000000100
    ```
    airmour
        6
    airmour  
       2020-08-20 13:59:42 +08:00   ❤️ 1
    new DecimalFormat("000000000000")
    qwerthhusn
        7
    qwerthhusn  
       2020-08-20 14:21:39 +08:00   ❤️ 1
    System.out.println(org.apache.commons.lang3.StringUtils.leftPad("123", 12, '0'));
    aguesuka
        8
    aguesuka  
       2020-08-20 19:38:17 +08:00
    5 楼是最优的。
    最简单的应该是 String.format("%10f", new BigDecimal("100"))
    aguesuka
        9
    aguesuka  
       2020-08-20 19:39:28 +08:00
    打错应该是这个 String.format("%010.0f", new BigDecimal(100))
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2783 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 564ms · UTC 12:51 · PVG 20:51 · LAX 05:51 · JFK 08:51
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.