格式化数字值从 XX.X 到 .XXX java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42306553/
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
Format number value from XX.X to .XXX java
提问by Kristy Welsh
I am receiving a value from a server that reads as a percentage, for example 77.5%. How can get the value .775 just using:
我从服务器接收一个以百分比形式读取的值,例如 77.5%。如何仅使用以下方法获得 .775 值:
String.format(Locale.getDefault(), formatPattern, floatValue);
I've consulted https://docs.oracle.com/javase/tutorial/java/data/numberformat.html, but it doesn't seem to cover my situation.
我已经咨询过https://docs.oracle.com/javase/tutorial/java/data/numberformat.html,但它似乎没有涵盖我的情况。
Note: I can only use the string format as we are placing the pattern into a config file.
注意:我只能使用字符串格式,因为我们将模式放入配置文件中。
回答by VHS
Try this:
试试这个:
String value = "75%";
Double aNumber = (Double.parseDouble(value.replace("%", "")))/100;
回答by mhmodsn
We can avoid the division by 100 and just moving the floating point to left two places by using :
我们可以避免除以 100,只需使用以下方法将浮点移动到左侧两个位置:
double value = java.math.BigDecimal.valueOf(77.5).movePointLeft(2).doubleValue();
回答by ahoxha
Does this work for you:
这对你有用吗:
String num = "75.5%";
String res = new DecimalFormat("#.000").format(Double.parseDouble(num.substring(0, num.length()-1))/100);