NumberFormat / DecimalFormat将某些浮点值视为长整型,而不是双精度 [英] NumberFormat/DecimalFormat treats certain floating-point values as longs instead of doubles
问题描述
NumberFormat / DecimalFormat似乎没有以#。0
格式(其中#是任何数字)作为双精度解析字符串。
以下代码说明了这一点:
NumberFormat/DecimalFormat doesn't seem to parse strings with the "#.0"
format (where # is any number) as a double.
The following code illustrates this:
#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
) - 两个字符串。
When parsing "2.0"
, the Formattable's type is 2 (Formattable::Type::kLong
). When parsing "2.1"
the Formattable's type is 1 (Formattable:Type::kDouble
) - as it should be for both strings.
当你尝试将浮点格式化为UnicodeString时也会出现问题(例如float 2.0 格式化为
2
)。
Issues also arise when you try to format a float as a UnicodeString (e.g. a float 2.0
gets formatted to "2"
).
因此:如何解析/作为ICU中的整数?
So: How can I parse/format any double number without it being interpreted as an integer in ICU?
推荐答案
可以调用 formattable.getDouble(status)
- getType返回long的唯一原因是特定的值将适合长。
You can call formattable.getDouble(status)
- the only reason getType returns long is that the particular value will fit in a long.
至于格式,如果在格式化之前调用 f-> setMinimumFractionDigits(1);
2.0与您的代码,设置最小数字为2给出2.00等。
As to format, if you call f->setMinimumFractionDigits(1);
before format, you will get "2.0" with your code, setting the min digits to 2 gives "2.00" etc.
hth
这篇关于NumberFormat / DecimalFormat将某些浮点值视为长整型,而不是双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!