Skip to content

Commit 0479309

Browse files
committed
Add value_doubleIsInt() function
1 parent b611cb1 commit 0479309

File tree

3 files changed

+25
-7
lines changed

3 files changed

+25
-7
lines changed

include/scratchcpp/value_functions.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ extern "C"
3434
LIBSCRATCHCPP_EXPORT char *value_toCString(const ValueData *v);
3535
LIBSCRATCHCPP_EXPORT void value_toUtf16(const ValueData *v, std::u16string *dst);
3636

37+
LIBSCRATCHCPP_EXPORT bool value_doubleIsInt(double v);
38+
3739
LIBSCRATCHCPP_EXPORT char *value_doubleToCString(double v);
3840
LIBSCRATCHCPP_EXPORT const char *value_boolToCString(bool v);
3941
LIBSCRATCHCPP_EXPORT double value_stringToDouble(const char *s);

src/scratch/value_functions.cpp

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -164,14 +164,9 @@ extern "C"
164164
case ValueType::Bool:
165165
return true;
166166

167-
case ValueType::Number: {
168-
if (std::isinf(v->numberValue) || std::isnan(v->numberValue))
169-
return true;
167+
case ValueType::Number:
168+
return value_doubleIsInt(v->numberValue);
170169

171-
double intpart;
172-
std::modf(v->numberValue, &intpart);
173-
return v->numberValue == intpart;
174-
}
175170
case ValueType::String:
176171
return value_checkString(v->stringValue) == 1;
177172
}
@@ -280,6 +275,17 @@ extern "C"
280275
dst->assign(utf8::utf8to16(s));
281276
}
282277

278+
/*! Returns true if the given number represents a round integer. */
279+
bool value_doubleIsInt(double v)
280+
{
281+
if (std::isinf(v) || std::isnan(v))
282+
return true;
283+
284+
double intpart;
285+
std::modf(v, &intpart);
286+
return v == intpart;
287+
}
288+
283289
/*!
284290
* Converts the given number to string.
285291
* \note It is the caller's responsibility to free allocated memory.

test/scratch_classes/value_test.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2795,6 +2795,16 @@ TEST(ValueTest, ComparisonOperators)
27952795
}
27962796
}
27972797

2798+
TEST(ValueTest, DoubleIsInt)
2799+
{
2800+
ASSERT_TRUE(value_doubleIsInt(0.0));
2801+
ASSERT_TRUE(value_doubleIsInt(15.0));
2802+
ASSERT_TRUE(value_doubleIsInt(-468.0));
2803+
ASSERT_FALSE(value_doubleIsInt(0.1));
2804+
ASSERT_FALSE(value_doubleIsInt(1.2));
2805+
ASSERT_FALSE(value_doubleIsInt(-12.5852));
2806+
}
2807+
27982808
TEST(ValueTest, DoubleToCString)
27992809
{
28002810
char *ret;

0 commit comments

Comments
 (0)