格式将Java/Android中至少一个重要的数字倍至至少一个重要的数字
-
09-10-2019 - |
题
我有一个分数对象,当我显示它们时,我用来将所有双重值格式化为一组数字(例如,假设2)。我希望它通常格式化为2个小数点,但我总是想要至少一个重要的数字。例如,如果我的价值为0.2,那么我的格式吐出了0.20,这很棒。但是,如果我的价值为0.000034,我的格式器将吐出0.00,我希望我的格式化器吐出0.00003。
Objective-C中的数字格式非常简单地做到这一点,我只能设置我想以2显示的最大数字数字,而最小数字的最小数字在1处产生我的所需输出,但是我该怎么做爪哇?
感谢任何人都能为我提供的帮助。
凯尔
编辑:我有兴趣舍入值,因此0.000037显示为0.00004。
解决方案
这不是有效的,因此,如果您经常执行此操作,我会尝试其他解决方案,但是如果您偶尔称呼它,则此方法将起作用。
import java.text.DecimalFormat;
public class Rounder {
public static void main(String[] args) {
double value = 0.0000037d;
// size to the maximum number of digits you'd like to show
// used to avoid representing the number using scientific notation
// when converting to string
DecimalFormat maxDigitsFormatter = new DecimalFormat("#.###################");
StringBuilder pattern = new StringBuilder().append("0.00");
if(value < 0.01d){
String s = maxDigitsFormatter.format(value);
int i = s.indexOf(".") + 3;
while(i < s.length()-1){
pattern.append("0");
i++;
}
}
DecimalFormat df = new DecimalFormat(pattern.toString());
System.out.println("value = " + value);
System.out.println("formatted value = " + maxDigitsFormatter.format(value));
System.out.println("pattern = " + pattern);
System.out.println("rounded = " + df.format(value));
}
}
其他提示
import java.math.BigDecimal;
import java.math.MathContext;
public class Test {
public static void main(String[] args) {
String input = 0.000034+"";
//String input = 0.20+"";
int max = 2;
int min =1;
System.out.println(getRes(input,max,min));
}
private static String getRes(String input,int max,int min) {
double x = Double.parseDouble(((new BigDecimal(input)).unscaledValue().intValue()+"").substring(0,min));
int n = (new BigDecimal(input)).scale();
String res = new BigDecimal(x/Math.pow(10,n)).round(MathContext.DECIMAL64).setScale(n).toString();
if(n<max){
for(int i=0;i<max;i++){
res+="0";
}
}
return res;
}
}
不隶属于 StackOverflow