Formato doble a al menos un dígito significativo en Java / Android
-
09-10-2019 - |
Pregunta
Tengo un objeto DecimalFormat el que estoy usando para dar formato a todos mis valores dobles para un número determinado de dígitos (digamos 2) cuando las estoy mostrando. Me gustaría que dar formato normalmente a 2 decimales, pero siempre quiero al menos un dígito significativo. Por ejemplo, si mi valor es 0,2 entonces mis formateador escupe 0.20 y eso es genial. Sin embargo, si mi valor es 0.000034 mi formateador se escupió 0.00 y yo preferiría mi saliva formateador cabo 0,00003.
Los formateadores de número en Objective-C hacen esto de manera muy sencilla, sólo puede establecer un número máximo de dígitos que quiero mostrar a los 2 y el número mínimo de dígitos significativos en 1 y se produce mi salida deseada, pero ¿cómo puedo hacerlo en Java?
Agradezco cualquier ayuda alguien me puede ofrecer.
Kyle
Editar:. Estoy interesado en el redondeo de los valores así como pantallas 0,000037 0,00004
Solución
No es eficiente, por lo que si realiza esta operación a menudo que me gustaría probar otra solución, pero si sólo se llama en ocasiones este método funcionará.
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));
}
}
Otros consejos
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;
}
}