c++ - NumberFormat/DecimalFormat 将某些浮点值视为 long 而不是 double

标签 c++ icu

NumberFormat/DecimalFormat 似乎无法将具有 "#.0" 格式(其中 # 是任意数字)的字符串解析为 double 字符串。 以下代码说明了这一点:

#include <cstdio>
#include <iostream>
#include <unicode/decimfmt.h>
#include <unicode/numfmt.h>
#include <unicode/unistr.h>
#include <unicode/ustream.h>

int main() {
    UErrorCode status = U_ZERO_ERROR;
    // DecimalFormat doesn't work either
    NumberFormat* f = NumberFormat::createInstance(status);
    f->setGroupingUsed(false);
    f->setParseIntegerOnly(false);

    UnicodeString str("2.0"); // Change to "2.#" for it to work, where # is any non-zero number
    Formattable formattable;
    f->parse(str, formattable, status);
    if (U_FAILURE(status)) {
        printf("ERROR: %s\n", u_errorName(status));
        delete f;
        return 1;
    } else {
        if (formattable.getType() == Formattable::kDouble) {
            printf("kDouble: %f\n", formattable.getDouble());
        } else if ((formattable.getType() == Formattable::kLong)) {
            printf("kLong: %d\n", formattable.getLong());
        } else {
            printf("ERROR: unexpected type: %d\n", formattable.getType());
        }
    }

    str.remove(); // Clear the string
    f->format(2.0f, str);
    std::cout << "formatted: \"" << str << '\"' << std::endl; // Outputs "2"
    delete f;

    return 0;
}

当解析"2.0"时,Formattable的类型是2(Formattable::Type::kLong)。解析 "2.1" 时,Formattable 的类型为 1 (Formattable:Type::kDouble) - 两个字符串都应如此。

当您尝试将 float 格式化为 UnicodeString 时也会出现问题(例如, float 2.0 被格式化为 "2")。

那么:我如何解析/格式化任何 double 而不在 ICU 中将其解释为整数?

最佳答案

您可以调用 formattable.getDouble(status) - getType 返回 long 的唯一原因是特定值适合 long。

关于格式,如果您在格式之前调用 f->setMinimumFractionDigits(1);,您的代码将得到“2.0”,将最小数字设置为 2 会得到“2.00”等。

第一个

关于c++ - NumberFormat/DecimalFormat 将某些浮点值视为 long 而不是 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3938834/

相关文章:

c++ - 专业类中的模板别名

c++ - 何时释放动态分配的 QObjects

c++ - 在Qt中释放文件锁

java - ICU4j SimpleDateFormatter 返回奇怪的结果

c++ - 如何在 multimap 的字符串中查找子字符串

c++ - 如何避免父类析构函数设置派生类的数据成员

c - 通过 ICU4C 进行 Unicode 规范化

c++ - ICU 正则表达式引用

Android NDK - 使用 ICU 支持构建 sqlite 时出错

internationalization - ICU 是否处理不同语言的字符串列表的整理?