rqxiao
V2EX  ›  Java

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

  •  
  •   rqxiao · Aug 20, 2020 · 2869 views
    This topic created in 2128 days ago, the information mentioned may be changed or developed.

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

    9 replies    2020-08-20 19:39:28 +08:00
    selca
        1
    selca  
       Aug 20, 2020
    转成 String 想怎么搞怎么搞
    k9990009
        2
    k9990009  
       Aug 20, 2020
    自己处理,返回的是 json 的话,重写 BigDecimal 的序列化方法就是了
    passerbytiny
        3
    passerbytiny  
       Aug 20, 2020 via Android
    不管原数据是啥类型,补零(或者任何格式化)后就变成 String 类型了,所以格式化自觉交给 String 体系去处理,BigDecimal 及任何数字类型都不用理会。
    crystom
        4
    crystom  
       Aug 20, 2020
    java 程序员也想要 leftpad [doge]
    chendy
        5
    chendy  
       Aug 20, 2020   ❤️ 3
    ```java
    DecimalFormat format = new DecimalFormat("000000000000");
    BigDecimal bigDecimal = new BigDecimal(100L);
    System.out.println(format.format(bigDecimal)); // 000000000100
    ```
    airmour
        6
    airmour  
       Aug 20, 2020   ❤️ 1
    new DecimalFormat("000000000000")
    qwerthhusn
        7
    qwerthhusn  
       Aug 20, 2020   ❤️ 1
    System.out.println(org.apache.commons.lang3.StringUtils.leftPad("123", 12, '0'));
    aguesuka
        8
    aguesuka  
       Aug 20, 2020
    5 楼是最优的。
    最简单的应该是 String.format("%10f", new BigDecimal("100"))
    aguesuka
        9
    aguesuka  
       Aug 20, 2020
    打错应该是这个 String.format("%010.0f", new BigDecimal(100))
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1031 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 54ms · UTC 23:31 · PVG 07:31 · LAX 16:31 · JFK 19:31
    ♥ Do have faith in what you're doing.