Skip to content

Commit 908249c

Browse files
committed
fix #478: Format bubble text according to Scratch 2.0
1 parent 4ce481f commit 908249c

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

src/scratch/target.cpp

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -570,8 +570,21 @@ const std::string &Target::bubbleText() const
570570
*/
571571
void Target::setBubbleText(const std::string &text)
572572
{
573+
// https://github.com/scratchfoundation/scratch-vm/blob/7313ce5199f8a3da7850085d0f7f6a3ca2c89bf6/src/blocks/scratch3_looks.js#L251-L257
574+
const Value v(text);
575+
std::string converted = text;
576+
577+
// Non-integers should be rounded to 2 decimal places (no more, no less), unless they're small enough that rounding would display them as 0.00.
578+
if (v.isValidNumber()) {
579+
const double num = v.toDouble();
580+
581+
if (std::abs(num) >= 0.01 && (v % 1).toDouble() != 0)
582+
converted = Value(std::round(num * 100) / 100).toString();
583+
}
584+
585+
// Limit the length of the string
573586
size_t limit = 330;
574-
impl->bubbleText = text.substr(0, limit);
587+
impl->bubbleText = converted.substr(0, limit);
575588
}
576589

577590
/*! Returns the engine. */

test/scratch_classes/target_test.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -780,6 +780,38 @@ TEST(TargetTest, BubbleText)
780780
target.setBubbleText(longstr);
781781
ASSERT_EQ(target.bubbleText().length(), 330);
782782
ASSERT_EQ(target.bubbleText(), longstr.substr(0, 330));
783+
784+
// Integers should be left unchanged
785+
target.setBubbleText("8");
786+
ASSERT_EQ(target.bubbleText(), "8");
787+
788+
target.setBubbleText("-52");
789+
ASSERT_EQ(target.bubbleText(), "-52");
790+
791+
target.setBubbleText("0");
792+
ASSERT_EQ(target.bubbleText(), "0");
793+
794+
// Non-integers should be rounded to 2 decimal places (no more, no less), unless they're small enough that rounding would display them as 0.00 (#478)
795+
target.setBubbleText("8.324");
796+
ASSERT_EQ(target.bubbleText(), "8.32");
797+
798+
target.setBubbleText("-52.576");
799+
ASSERT_EQ(target.bubbleText(), "-52.58");
800+
801+
target.setBubbleText("3.5");
802+
ASSERT_EQ(target.bubbleText(), "3.5");
803+
804+
target.setBubbleText("0.015");
805+
ASSERT_EQ(target.bubbleText(), "0.02");
806+
807+
target.setBubbleText("-0.015");
808+
ASSERT_EQ(target.bubbleText(), "-0.02");
809+
810+
target.setBubbleText("0.005");
811+
ASSERT_EQ(target.bubbleText(), "0.005");
812+
813+
target.setBubbleText("-0.005");
814+
ASSERT_EQ(target.bubbleText(), "-0.005");
783815
}
784816

785817
TEST(TargetTest, Engine)

0 commit comments

Comments
 (0)