【问题标题】:Spelled-out number (string) to integer using ICU使用 ICU 将数字(字符串)拼写为整数
【发布时间】:2019-09-12 17:02:09
【问题描述】:

我需要将字符串转换为整数。例如,我想将 6 转换为 6。

我使用 IBM 的库 ICU 进行了相反的操作(6 → 第六)。

private val String.spellout: String
  get() {
    val esFormatter = RuleBasedNumberFormat(Locale.ENGLISH, RuleBasedNumberFormat.SPELLOUT)
    return esFormatter.format(this.toDouble(), "%spellout-ordinal")
  }

我想创建另一种方法,该方法采用该拼写字符串并将其转换为双精度(第六→ 6)

【问题讨论】:

  • 你试过icu-project.org/apiref/icu4j/com/ibm/icu/text/…,例如val esFormatter = RuleBasedNumberFormat(Locale.ENGLISH, RuleBasedNumberFormat.ORDINAL); val n = esFormatter.parse("sixth")
  • RuleBasedNumberFormat 也有一个 parse 方法,看起来它正在做你想做的事。
  • 你们是对的。我试过了,但也将它用于无效字符串,所以它抛出了异常。我不得不用 try-catch 来包装它。

标签: java kotlin icu


【解决方案1】:

从 cmets 获得帮助后,这是我的解决方案,以防其他人需要它:

private val String.numberFromSpelledOut: Boolean
  get() {
    val esFormatter = RuleBasedNumberFormat(Locale.ENGLISH, RuleBasedNumberFormat.SPELLOUT)
    return try {
      return esFormatter.parse(this)
    } catch (e: ParseException) {
      ""
    }
  }

这不应该为无效的拼写输入抛出异常。

【讨论】:

  • “这不应该为无效的拼写输入抛出异常。”当然,这是您的选择;但根据我的经验,从长远来看,它往往会导致更大的问题。 (如果对这种特殊需求有意义,您可以让numberFromSpelledOut 抛出异常,然后让调用者捕获它。这会更明确,更灵活。虽然如果它可以抛出异常,它可能会产生更多感觉是一种扩展方法而不是扩展属性。)
猜你喜欢
  • 2020-07-14
  • 2015-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
  • 2011-04-12
相关资源
最近更新 更多