java中小数点后的字符串修剪为18位 - 不需要四舍五入)

发布于 2025-01-12 13:32:25 字数 441 浏览 3 评论 0原文

我正在开发一个遗留代码,其中有一个 String 字段,其中包含一些金额值,小数点后应该只有 18 个字符,不能超过这个值。

我已经实现了如下所示 -

        String str = "0.0040000000000000001";
    String[] values = StringUtils.split(str,".");
    System.out.println(str);
    String output = values[1];
    if(output.length()>18){
        output = output.substring(0,18);
    }
    System.out.println(values[0]+"."+output); // 0.004000000000000000

有没有更好的方法来做到这一点?

I am working on a legacy code where i have String field which hold some amount value, which should have only 18 char after decimal place, not more than that.

I have achieved this like below -

        String str = "0.0040000000000000001";
    String[] values = StringUtils.split(str,".");
    System.out.println(str);
    String output = values[1];
    if(output.length()>18){
        output = output.substring(0,18);
    }
    System.out.println(values[0]+"."+output); // 0.004000000000000000

Is there any better way to do this ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

污味仙女 2025-01-19 13:32:25

使用正则表达式实现一行解决方案:

str = str.replaceAll("(?<=\\..{18}).*", "");

请参阅现场演示

Use regex for a one line solution:

str = str.replaceAll("(?<=\\..{18}).*", "");

See live demo.

川水往事 2025-01-19 13:32:25

将其放入一个方法中,并测试几种替代方案,看看哪个更好。您必须首先定义“更好”对于您的特定用例意味着什么:更少的内存?快点?

我建议:

public static String trimDecimalPlaces(String input, int places) {
    int dotPosition = input.indexOf(".");
    int targetSize = dotPosition + places + 1;
    if (dotPosition == -1 || targetSize > input.length()) {
        return input;
    } else {
        return input.substring(0, targetSize);
    }
}

这比基于正则表达式的解决方案具有速度优势,但就代码而言肯定更长。

Put it in a method, and test several alternatives to see which is better. You will have to first define what "better" means for your specific use-case: less memory? faster?

I propose:

public static String trimDecimalPlaces(String input, int places) {
    int dotPosition = input.indexOf(".");
    int targetSize = dotPosition + places + 1;
    if (dotPosition == -1 || targetSize > input.length()) {
        return input;
    } else {
        return input.substring(0, targetSize);
    }
}

This has a speed advantage over regex-based solutions, but it is certainly longer in terms of code.

陪你搞怪i 2025-01-19 13:32:25

您可以在此处使用正则表达式替换:

String str = "0.0040000000000000001";
String output = str.replaceAll("(\\d+\\.\\d{18})(\\d+)", "$1");
System.out.println(output); // 0.004000000000000000

You could use a regex replacement here:

String str = "0.0040000000000000001";
String output = str.replaceAll("(\\d+\\.\\d{18})(\\d+)", "$1");
System.out.println(output); // 0.004000000000000000
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文