fix(NumberFormatter): Negative precision in NumberFormatter::format() #2511

This commit is contained in:
Alex Fabijanic 2022-06-24 09:59:30 +02:00
parent 79f7b43dc4
commit ae00f1c8eb
2 changed files with 22 additions and 0 deletions

View File

@ -849,6 +849,8 @@ inline std::string NumberFormatter::format(float value)
inline std::string NumberFormatter::format(float value, int precision)
{
if (precision < 0)
throw InvalidArgumentException("NumberFormatter::format() requires non-negative precision.");
char buffer[POCO_MAX_FLT_STRING_LEN];
floatToFixedStr(buffer, POCO_MAX_FLT_STRING_LEN, value, precision);
return std::string(buffer);
@ -857,6 +859,8 @@ inline std::string NumberFormatter::format(float value, int precision)
inline std::string NumberFormatter::format(float value, int width, int precision)
{
if (precision < 0)
throw InvalidArgumentException("NumberFormatter::format() requires non-negative precision.");
std::string result;
floatToFixedStr(result, value, precision, width);
return result;
@ -873,6 +877,8 @@ inline std::string NumberFormatter::format(double value)
inline std::string NumberFormatter::format(double value, int precision)
{
if (precision < 0)
throw InvalidArgumentException("NumberFormatter::format() requires non-negative precision.");
char buffer[POCO_MAX_FLT_STRING_LEN];
doubleToFixedStr(buffer, POCO_MAX_FLT_STRING_LEN, value, precision);
return std::string(buffer);
@ -881,6 +887,8 @@ inline std::string NumberFormatter::format(double value, int precision)
inline std::string NumberFormatter::format(double value, int width, int precision)
{
if (precision < 0)
throw InvalidArgumentException("NumberFormatter::format() requires non-negative precision.");
std::string result;
doubleToFixedStr(result, value, precision, width);
return result;

View File

@ -263,6 +263,20 @@ void NumberFormatterTest::testFormatFloat()
assertTrue (NumberFormatter::format(50.546, 0) == "51");
assertTrue (NumberFormatter::format(50.546f, 0) == "51");
assertTrue (NumberFormatter::format(50.546f, 2) == "50.55");
try
{
Poco::NumberFormatter::format(0.1, -1);
fail ("NumberFormatter::format() must throw on negative precision");
}
catch(Poco::InvalidArgumentException&){}
try
{
Poco::NumberFormatter::format(0.1, 2, -1);
fail ("NumberFormatter::format() must throw on negative precision");
}
catch(Poco::InvalidArgumentException&){}
}