Pregunta

public class Test {
    public static void main(String[] args) {
        final String test1 = new String("01,");
        final String test2 = new String("01,0");
        final String test3 = new String("1,00");

        String pattern = "##,##";
        DecimalFormat formatter;
        DecimalFormatSymbols dfs = new DecimalFormatSymbols();
        dfs.setGroupingSeparator(',');

        formatter = new DecimalFormat(pattern, dfs);
        String result1 = formatter.format(test1);
        String result2 = formatter.format(test2);
        String result3 = formatter.format(test3);

        System.out.println("Result 1 == " + result1);
        System.out.println("Result 2 == " + result2);
        System.out.println("Result 3 == " + result3);
    }
}

I am trying to format the string. I added the code which I am using for formatting. I am getting exception.

I want result as 01,00 for all of this.

EXCEPTION -

Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Number
    at java.text.DecimalFormat.format(DecimalFormat.java:487)
    at java.text.Format.format(Format.java:140)
    at com.test.Test.main(Test.java:21)

If anyone has any idea please guide me.

¿Fue útil?

Solución

DecimalFormat.format accepts only Date or Number objects, not String!

EDIT-1:

1) String pattern = "00.00"

2)

        String result1 = formatter.format(formatter.parse(test1));
        String result2 = formatter.format(formatter.parse(test2));
        String result3 = formatter.format(formatter.parse(test3));

For example: for

    final String test1 = new String("01,");
    final String test2 = new String("02,3");
    final String test3 = new String("1,00");

it gives me:

Result 1 == 01,00
Result 2 == 02,30
Result 3 == 01,00

Otros consejos

This is how it should be used.

format = new DecimalFormat(".00");
format.format(10.0);
String s = (String.format("%,d", 1000000)).replace(',', ' ');
    int minutes = (int) secondsLeft / 60;
    int seconds = secondsLeft - minutes * 60;

    String upDatePattern ;
    upDatePattern = (String.format("%02d:%02d", minutes,seconds));
    timerTextView.setText(upDatePattern);

    this produces a zero padded "timer" with min/sec
     ex: 02:35
 you can find lots of formatting examples on "Formatter | Android Developers
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top