DecimalFormat Float上的NumberFormatException

时间:2015-03-21 16:43:52

标签: android floating-point numberformatexception textwatcher

经过多次尝试,我设法为Float创建了一个模式,我设法通过返回ActivityResult并在相应的字段中设置它。现在我有一个问题,这个TextWatcher不接受Float模式,任何人都可以帮助我吗?

这是TextWather

   private abstract class TextChangedListener implements TextWatcher
{

    public abstract void numberEntered(Float number);

    @Override
    public void afterTextChanged(Editable s)
    {
        String text = s.toString();
        try
        {
            Float parsedFloat = Float.valueOf(text);
            numberEntered(parsedFloat);
        } catch (NumberFormatException e)
        {
            Log.w(getPackageName(), "Non si puo' parsare '" + text + "' col numero", e);
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after)
    {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count)
    {
    }
}

这是Float模式

DecimalFormat dec = new DecimalFormat("###,##0.00", DecimalFormatSymbols.getInstance(Locale.ITALIAN));

2 个答案:

答案 0 :(得分:1)

感谢大家!我用这种方法解决了我的问题!

    private void decimalFormatWithSymbol() {
    dec = new DecimalFormat("##0.00", DecimalFormatSymbols.getInstance(Locale.ITALIAN));
    dfs = new DecimalFormatSymbols();
    dfs.setDecimalSeparator('.');
    dec.setDecimalFormatSymbols(dfs);
    }

答案 1 :(得分:0)

如果您想为float提供一些小数,请将其转换为double

float f = 90;
DecimalFormat decimal2 = new DecimalFormat("#.##"); // gives 2 numbers after '.'
double dec = Double.valueOf(decimal2.format(f));

上面的代码将为您提供输出:

90.00