java中小数点后的字符串修剪为18位 - 不需要四舍五入)
我正在开发一个遗留代码,其中有一个 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用正则表达式实现一行解决方案:
请参阅现场演示。
Use regex for a one line solution:
See live demo.
将其放入一个方法中,并测试几种替代方案,看看哪个更好。您必须首先定义“更好”对于您的特定用例意味着什么:更少的内存?快点?
我建议:
这比基于正则表达式的解决方案具有速度优势,但就代码而言肯定更长。
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:
This has a speed advantage over regex-based solutions, but it is certainly longer in terms of code.
您可以在此处使用正则表达式替换:
You could use a regex replacement here: