瀏覽代碼

Fix bug with rescaling

Sam Jaffe 7 年之前
父節點
當前提交
bf8f524dfb
共有 2 個文件被更改,包括 21 次插入3 次删除
  1. 2 2
      src/bigdecimal.cpp
  2. 19 1
      test/bigdecimal_test.cpp

+ 2 - 2
src/bigdecimal.cpp

@@ -114,8 +114,8 @@ void bigdecimal::rescale(int32_t nscale) {
   }
   auto const idx = -nscale % SEG_DIGITS;
   if (scale() > nscale && nscale < 0 && idx) {
-    data.back() /= detail::powers[idx];
-    data.back() *= detail::powers[idx];
+    data.front() /= detail::powers[idx];
+    data.front() *= detail::powers[idx];
   }
   set_scale(nscale);
 }

+ 19 - 1
test/bigdecimal_test.cpp

@@ -18,6 +18,10 @@ TEST(BigDecimalTest, ConstructDecimal) {
   EXPECT_THAT(math::bigdecimal("1000.01").to_string(), "1000.01");
 }
 
+TEST(BigDecimalTest, ConstructIntWithScaleAndStep) {
+  EXPECT_THAT(math::bigdecimal(1000000000, -2).to_string(), "1000000000");
+}
+
 TEST(BigDecimalTest, RescalePositiveAddsDecimalPlaces) {
   math::bigdecimal dec(100);
   EXPECT_THAT(dec.scale(), 0);
@@ -84,7 +88,8 @@ TEST(BigDecimalTest, SubtractionNormalizeScaleToHighest) {
 }
 
 struct ArithTuple { math::bigdecimal lhs, rhs; std::string expected; };
-void PrintTo(ArithTuple const & tup, std::ostream * out) {
+struct BigDecPair { math::bigdecimal lhs, rhs; };
+void PrintTo(BigDecPair const & tup, std::ostream * out) {
   (*out) << "{ lhs = " << tup.lhs.to_string() << "(" << tup.lhs.scale() << "), rhs = " << tup.rhs.to_string() << "(" << tup.rhs.scale() << ") }";
 }
 
@@ -106,6 +111,12 @@ TEST_P(DivisionScaleTest, ScaleIsDifferenceOfNumAndDenomScales) {
   EXPECT_THAT(out.to_string(), tup.expected);
 }
 
+class EqTest : public testing::TestWithParam<BigDecPair> {};
+
+TEST_P(EqTest, DecimalsAreEqualEvenIfScalesAreNot) {
+  EXPECT_THAT(GetParam().lhs, GetParam().rhs);
+}
+
 #pragma clang diagnostic push
 #pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
 INSTANTIATE_TEST_CASE_P(BigDecimal, MultiplicationScaleTest,
@@ -133,4 +144,11 @@ INSTANTIATE_TEST_CASE_P(BigDecimal, DivisionScaleTest,
                                         ArithTuple{{1, 5}, {1000000000, -9}, "0.00000000100000"},
                                         ArithTuple{{100, -2}, {1000000000, -9}, "0.0000001"},
                                         ArithTuple{{10000, -4}, {100000, -5}, "0.1"}));
+
+INSTANTIATE_TEST_CASE_P(BigDecimal, EqTest,
+                        testing::Values(BigDecPair{{  0}, {  0,  4}},
+                                        BigDecPair{{100}, {100, -2}},
+                                        BigDecPair{{1000000000}, {1000000000, -9}},
+                                        BigDecPair{{"0.1", 1}, {"0.10", 2}}));
+
 #pragma clang diagnostic pop