Java 如何将百分比字符串转换为 BigDecimal?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9713309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:34:55 来源:igfitidea点击:
how to convert percentage String to BigDecimal?
提问by user595234
In java, how to convert percentage String to BigDecimal ?
在java中,如何将百分比字符串转换为BigDecimal?
Thanks
谢谢
String percentage = "10%";
BigDecimal d ; // I want to get 0.1
采纳答案by Eng.Fouad
BigDecimal d = new BigDecimal(percentage.trim().replace("%", "")).divide(BigDecimal.valueOf(100));
回答by Jon Egeland
As long as you know that the %
symbol will always be at the end of your String
:
只要您知道该%
符号将始终位于您的 末尾String
:
BigDecimal d = new BigDecimal(percentage.substring(0, percentage.length()-1));
d.divide(100); // '%' means 'per hundred', so divide by 100
If you don't know that the %
symbol will be there:
如果您不知道该%
符号将在那里:
percentage = percentage.replaceAll("%", ""); // Check for the '%' symbol and delete it.
BigDecimal d = new BigDecimal(percentage.substring(0, percentage.length()-1));
d.divide(new BigDecimal(100));
回答by namalfernandolk
Try new DecimalFormat("0.0#%").parse(percentage)
尝试 new DecimalFormat("0.0#%").parse(percentage)