rqxiao
V2EX  ›  Java

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

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