MCPcopy Create free account
hub / github.com/bbuchfink/diamond / format

Function format

src/util/string/string.cpp:180–240  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

178}
179
180string format(double number) {
181 const vector<string> suffixes = { "", "K", "M", "G", "T", "P", "E" };
182
183 if (number == 0) {
184 return "0";
185 }
186
187 bool is_negative = number < 0;
188 double abs_number = std::abs(number);
189
190 int suffix_index = 0;
191 if (abs_number >= 1000) {
192 int exp = static_cast<int>(std::log10(abs_number) / 3);
193 suffix_index = std::min(exp, static_cast<int>(suffixes.size() - 1));
194 }
195
196 double divisor = std::pow(1000.0, suffix_index);
197 double formatted_number = abs_number / divisor;
198
199 std::ostringstream oss;
200 oss << std::fixed << std::setprecision(2) << formatted_number;
201 string num_str = oss.str();
202
203 // Trim trailing zeros and decimal point if needed
204 size_t dot_pos = num_str.find('.');
205 if (dot_pos != std::string::npos) {
206 // Find the last non-zero character after the decimal point
207 size_t last_non_zero = num_str.find_last_not_of('0');
208 if (last_non_zero != std::string::npos) {
209 num_str = num_str.substr(0, last_non_zero + 1);
210 // If the decimal point is now at the end, remove it
211 if (num_str.back() == '.') {
212 num_str.pop_back();
213 }
214 }
215 }
216
217 // Check if after trimming, the number is 1000 or more, adjust suffix if possible
218 if (formatted_number >= 999.995 && suffix_index < (int)suffixes.size() - 1) {
219 suffix_index++;
220 divisor *= 1000;
221 formatted_number = abs_number / divisor;
222 oss.str("");
223 oss << std::fixed << std::setprecision(2) << formatted_number;
224 num_str = oss.str();
225 // Trim again
226 dot_pos = num_str.find('.');
227 if (dot_pos != std::string::npos) {
228 size_t last_non_zero = num_str.find_last_not_of('0');
229 if (last_non_zero != std::string::npos) {
230 num_str = num_str.substr(0, last_non_zero + 1);
231 if (num_str.back() == '.') {
232 num_str.pop_back();
233 }
234 }
235 }
236 }
237

Callers 7

splitFunction · 0.50
get_seqMethod · 0.50
write_unalignedFunction · 0.50
write_alignedFunction · 0.50
align_queriesFunction · 0.50
write_repsFunction · 0.50
write_blocksFunction · 0.50

Calls 6

log10Function · 0.85
minFunction · 0.85
backMethod · 0.80
pop_backMethod · 0.80
sizeMethod · 0.45
findMethod · 0.45

Tested by

no test coverage detected