Java BigDecimal 不用科学计数法输出,去前导零 51Nod 1873

本文介绍了在Java中处理高精度浮点数时如何避免科学计数法的显示以及去除前导零的方法。通过stripTrailingZeros()方法可以移除末尾多余的0,而toPlainString()方法确保不使用科学计数法进行输出。若要删除字符串形式的高精度浮点数开头的'0.',只需进行简单的字符串处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java高精度确实A题利器,但是也需要掌握一定的技巧,尤其控制精度方面,由于大浮点数精度太高就默认用科学计数法表示,这里我们可以略施小计让其不用科学计数法表示并且去掉前导“0.”


stripTrailingZeros() :用于去除末尾多余的0

toPlainString(): 控制不使用科学计数法输出

去掉前导“0.”就相对简单多了,只需要先将高精度浮点数转化为字符串再判断字符串开头即可。


import java.io.BufferedInputStream;
import java.math.BigDecimal;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner cin = new Scanner(new BufferedInputStream(System.in));
        BigDecimal a;
        int b;
        while(cin.hasNext()) {
            a = cin.nextBigDecimal();
            b = cin.nextInt();
            BigDecimal ans = BigDecimal.ONE;
            while(b != 0) {
                if(b % 2 == 1) {
                    ans = ans.multiply(a);
                }
                a = a.multiply(a);
                b >>= 1;
            }
            String str = ans.stripTrailingZeros().toPlainString();
            if(str.startsWith("0.")) {
                str = str.substring(1, str.length());
            }
            System.out.println(str);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值