Java's BigDecimal series--remove the extra 0 at the end of the decimal

Original website: Java's BigDecimal series--remove the extra 0 at the end of the decimal

Introduction

illustrate

This article introduces the method of Java to remove the extra 0 at the end of the BigDecimal decimal.

overview

BigDecimal provides the stripTrailingZeros() method to remove the 0 at the end of the decimal.

Calling stripTrailingZeros() and then calling toString() will convert to scientific notation output. If you do not want to output in scientific notation, you can use toPlainString() for full character output.

example

package com.example.a;

import java.math.BigDecimal;

public class Demo {
    public static void main(String[] args) {
        BigDecimal bigNumber = new BigDecimal("3222.4300");

        System.out.println(bigNumber.toString());
        System.out.println(bigNumber.stripTrailingZeros().toString());
        System.out.println(bigNumber.stripTrailingZeros().toPlainString());

        System.out.println("-----------------------------");
        bigNumber = new BigDecimal("3222000");

        System.out.println(bigNumber.toString());
        System.out.println(bigNumber.stripTrailingZeros().toString());
        System.out.println(bigNumber.stripTrailingZeros().toPlainString());
    }
}

result

3222.4300
3222.43
3222.43
-----------------------------
3222000
3.222E+6
3222000

Guess you like

Origin blog.csdn.net/feiying0canglang/article/details/128189632