Cómo rellenar números con guiones bajos en Java, en lugar de los ceros habituales?Cómo rellenar números con guiones bajos en Java?
Por ejemplo quiero
- 123,45 para ser formateados a ___ 123.45 y
- 12.345,67 para ser formateados a _12345.67
- 0.12 para ser formateados a _ __ _ __ .12
Probé muchas cosas y lo más cerca que conseguí Fue este (mediante el uso de SYMBOLS.setZeroDigit ('_');):
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
public class Example {
public static void main(String[] args) {
DecimalFormatSymbols SYMBOLS = new DecimalFormatSymbols();
SYMBOLS.setDecimalSeparator('.');
SYMBOLS.setGroupingSeparator(',');
DecimalFormat OUTPUT_FORMAT = new DecimalFormat("000,000.00", SYMBOLS);
System.out.println(OUTPUT_FORMAT.format(0.01));
// got 000,000.01
System.out.println(OUTPUT_FORMAT.format(0.12));
// got 000,000.12
System.out.println(OUTPUT_FORMAT.format(123456));
// got 123,456.00
System.out.println(OUTPUT_FORMAT.format(123456.78));
// got 123,456.78
System.out.println(OUTPUT_FORMAT.format(1234));
// got 001,234.00
System.out.println(OUTPUT_FORMAT.format(1234.56));
// got 001,234.56
SYMBOLS.setZeroDigit('_');
OUTPUT_FORMAT = new DecimalFormat("000,000.00", SYMBOLS);
System.out.println(OUTPUT_FORMAT.format(0.01));
// expected ______._1 but got ___,___._`
System.out.println(OUTPUT_FORMAT.format(0.12));
// expected ______.12 but got ___,___.`a
System.out.println(OUTPUT_FORMAT.format(123456));
// expected 123,456.__ but got `ab,cde.__
System.out.println(OUTPUT_FORMAT.format(123456.78));
// expected 123,456.78 but got `ab,cde.fg
System.out.println(OUTPUT_FORMAT.format(1234));
// expected __1,234.00 or at least __1,234.__ but got __`,abc.__
System.out.println(OUTPUT_FORMAT.format(1234.56));
// expected __1,234.56 but got __`,abc.de
}
}
Bueno, no realmente cerca, pero un número vacía si la derecha con formato (con guiones al final): _ __ ,_ __. __
De todos modos, sugerencias sobre cómo conseguir el comportamiento esperado?
'DecimalFormatSymbols.setZeroDigit' se utiliza para configurar el carácter para representar cero ** y todos los demás dígitos que le siguen **. 'sigue a' _' y es por eso que estás viendo '___, ___._' 'en lugar de' ___, ___._ 1' Editar: el formateo no funciona pero entiendes el punto, supongo. –
sí, sé cómo funciona setZeroDigit pero estaba pidiendo una solución para lograr el esperado – Belun