【问题标题】:Android Localization queryAndroid 本地化查询
【发布时间】:2015-03-06 10:10:22
【问题描述】:

我一直在为我的应用程序进行本地化,但似乎找不到任何有关如何处理来自不同本地人的十进制值和日期以存储在 sqllite 中的信息。

例如: 德国十进制 123,53 英国十进制 123.53

那么如何将edittext 字段转换为有效的小数。目前,我将代码输出到 textview 而不是 sql 仅用于测试。下面的代码在使用英国小数时效果很好,但如果我使用德国小数,它就会失败!!

 Configuration sysConfig = getResources().getConfiguration();
 Locale curLocale = sysConfig.locale;
 NumberFormat nf = NumberFormat.getInstance(curLocale);
 String convertedString = nf.format(Double.parseDouble(EditTextField.getText().toString()));

 TextView showLocalisedNumeric;
 showLocalisedNumeric = (TextView)findViewById(R.id.TestNumericValue);
 showLocalisedNumeric.setText(convertedString);

我还没有开始使用日期,但我假设将日期转换为更直接。

【问题讨论】:

  • how to handle decimal values and dates from different locals to store in sqllite. - 以 SQLite 可以理解的格式存储值。对于日期,有效格式为Time String,如sqlite.org/lang_datefunc.html 中所定义。如何向用户展示它是另一个问题。您可能会使用SimpleDateFormat
  • 谢谢,但我已经了解这方面,我要问的是如何在不使用替换方法的情况下将其转换为例如 123,45 到 123.45 的格式
  • 将十进制值存储在 REAL 字段中。然后使用DecimalFormat 向用户展示

标签: java android localization number-formatting


【解决方案1】:

经过一段时间的研究,我找到了本地化解决方案,从输入中获取一个值并将其解析为 SQLlite 可以理解的格式 - 对于本练习并减少代码,我刚刚将其设置为输出文本视图。

 // set initial value to variables
    String convertedString = "";
    double parsedValue = 0.0;

    //get value from text field
    EditText EditTextField  =(EditText)findViewById(R.id.TestNumericValueEntered);
    String valueFromInput = EditTextField.getText().toString();

    //Get current Locale from system
    Configuration sysConfig = getResources().getConfiguration();
    Locale curLocale = sysConfig.locale;

    //Set number formats
    NumberFormat nf_in = NumberFormat.getNumberInstance(curLocale);
    NumberFormat nf_out = NumberFormat.getNumberInstance(Locale.UK);

    //try to parse value, otherwise return error message
    try {
        parsedValue = nf_in.parse(valueFromInput).doubleValue();
        // use nf_out.setMaximumFractionDigits(3) to set max number of digits allowed after decimal;
        convertedString = nf_out.format(parsedValue);
    }catch(ParseException e){
        convertedString = "Unable to translate value";
    }
    //Output result
    TextView showLocalisedNumeric;
    showLocalisedNumeric = (TextView)findViewById(R.id.TestNumericValue);
    showLocalisedNumeric.setText(convertedString);

当我添加这个答案时,我意识到对代码的一个很好的补充是检查当前语言环境是否与您计划解析的语言环境相同,如果是,则可以跳过转换(解析)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 2018-12-20
    相关资源
    最近更新 更多