Skip to content

Commit ba14cf8

Browse files
committed
fix #478: Format bubble text according to Scratch 2.0
1 parent 85f96a7 commit ba14cf8

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
@@ -576,8 +576,21 @@ const std::string &Target::bubbleText() const
576576
*/
577577
void Target::setBubbleText(const std::string &text)
578578
{
579+
// https://github.com/scratchfoundation/scratch-vm/blob/7313ce5199f8a3da7850085d0f7f6a3ca2c89bf6/src/blocks/scratch3_looks.js#L251-L257
580+
const Value v(text);
581+
std::string converted = text;
582+
583+
// 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.
584+
if (v.isValidNumber()) {
585+
const double num = v.toDouble();
586+
587+
if (std::abs(num) >= 0.01 && (v % 1).toDouble() != 0)
588+
converted = Value(std::round(num * 100) / 100).toString();
589+
}
590+
591+
// Limit the length of the string
579592
size_t limit = 330;
580-
impl->bubbleText = text.substr(0, limit);
593+
impl->bubbleText = converted.substr(0, limit);
581594
}
582595

583596
/*! Returns the engine. */

test/scratch_classes/target_test.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -781,6 +781,38 @@ TEST(TargetTest, BubbleText)
781781
target.setBubbleText(longstr);
782782
ASSERT_EQ(target.bubbleText().length(), 330);
783783
ASSERT_EQ(target.bubbleText(), longstr.substr(0, 330));
784+
785+
// Integers should be left unchanged
786+
target.setBubbleText("8");
787+
ASSERT_EQ(target.bubbleText(), "8");
788+
789+
target.setBubbleText("-52");
790+
ASSERT_EQ(target.bubbleText(), "-52");
791+
792+
target.setBubbleText("0");
793+
ASSERT_EQ(target.bubbleText(), "0");
794+
795+
// 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)
796+
target.setBubbleText("8.324");
797+
ASSERT_EQ(target.bubbleText(), "8.32");
798+
799+
target.setBubbleText("-52.576");
800+
ASSERT_EQ(target.bubbleText(), "-52.58");
801+
802+
target.setBubbleText("3.5");
803+
ASSERT_EQ(target.bubbleText(), "3.5");
804+
805+
target.setBubbleText("0.015");
806+
ASSERT_EQ(target.bubbleText(), "0.02");
807+
808+
target.setBubbleText("-0.015");
809+
ASSERT_EQ(target.bubbleText(), "-0.02");
810+
811+
target.setBubbleText("0.005");
812+
ASSERT_EQ(target.bubbleText(), "0.005");
813+
814+
target.setBubbleText("-0.005");
815+
ASSERT_EQ(target.bubbleText(), "-0.005");
784816
}
785817

786818
TEST(TargetTest, Engine)

0 commit comments

Comments
 (0)