Search code examples
javaformatbigdecimal

Format BigDecimal or Number without Decimal Separator


Hi i want to print a number with decimal values but without using decimal separator.

Ex: i have this 275.1234 but i want this 027512 (4 Digit 2 Decimal, all without separator)

i tried two approaches:

    DecimalFormat format = new DecimalFormat("0000.00");  
    DecimalFormatSymbols custom=new DecimalFormatSymbols();
    custom.setDecimalSeparator('\u0000');
    format.setDecimalFormatSymbols(custom);
    System.out.println(format.format(new BigDecimal("275.1234")));

This print me: 0275 12 (i knew i can remove the space)

Second Approach:

    String[] value = new BigDecimal("275.1234").toString().split("\\.");
    System.out.println(value[0] + value[1].substring(0,2));

This print me: 27512 (Bad I need That The First 4 digits are filled with 0 if the number in question does not have integer 4 digits)

Ex: 1,1234 ==> 000112
Ex: 10,5678 ==> 001056
Ex: 100,7877 ==> 010078

Basically i want more elegant solution to this problem, any ideas?

Thanks Ignacio


Solution

  • How about multiplying by 100.

    String text = String.format("%06.0f", Double.parseDouble("275.1234")*100);
    

    or

    String text = String.format("%06.0f", 275.1234 * 100);
    

    or

    String text = String.format("%06.0f", BigDecimal.valueOf(275.1234).doubleValue() * 100);
    

    sets text to

    027512
    

    If you want to truncate rather than round you can do

    String text = String.format("%06d", (long) (1234.5678 * 100));
    

    prints

    123456