Skip to content

Commit 8c76fe2

Browse files
committed
fix: Resolve exceptions caused by long string construction
1 parent c30dc01 commit 8c76fe2

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

moxt/fixed12.cpp

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -116,8 +116,23 @@ SEQ_FUNC fixed12_t fixed12_new_string_view(const std::string_view &s) {
116116
}
117117

118118
std::string fs(s_.substr(period + 1));
119-
fs += std::string(12 - fs.length(), '0');
120-
f = strtoi(fs.substr(0, 12));
119+
if (fs.length() > MAX_FRAC_BITS) {
120+
// 对小数部分进行四舍五入
121+
int64_t decimalPart =
122+
strtoi(fs.substr(0, MAX_FRAC_BITS + 1)); // 考虑到四舍五入的情况
123+
if (decimalPart % 10 >= 5) {
124+
fs = std::to_string(decimalPart / 10 +
125+
1); // 四舍五入并转换回字符串
126+
} else {
127+
fs = std::to_string(decimalPart / 10); // 四舍五入并转换回字符串
128+
}
129+
fs = fs.substr(0, MAX_FRAC_BITS); // 确保只取前12位
130+
} else {
131+
fs += std::string(MAX_FRAC_BITS - fs.length(),
132+
'0'); // 如果小于12位,补零
133+
}
134+
auto a = fs.substr(0, MAX_FRAC_BITS);
135+
f = strtoi(fs.substr(0, MAX_FRAC_BITS));
121136
}
122137
return sign * (i * FIXED_SCALE + f);
123138
}

0 commit comments

Comments
 (0)