insertSpaces method
Returns a String with spaces added according to SI guidelines.
Implementation
String insertSpaces(String str) {
// Remove any exponent piece and add it back in after spaces are added.
final expIndex = _exponentIndex(str);
final numStr = expIndex != -1 ? str.substring(0, expIndex) : str;
final decimalIndex = numStr.indexOf('.');
final preCount = decimalIndex != -1 ? decimalIndex : numStr.length;
final postCount = decimalIndex != -1 ? numStr.length - decimalIndex - 1 : 0;
final buf = StringBuffer();
// Pre-decimal.
if (preCount > 4) {
final preStr =
decimalIndex != -1 ? numStr.substring(0, decimalIndex) : numStr;
final fullGroups = preStr.length ~/ 3;
var cursor = preStr.length - fullGroups * 3;
if (cursor != 0) buf.write(preStr.substring(0, cursor));
while (cursor + 3 <= preStr.length) {
if (cursor != 0) buf.write(unicode ? '\u{2009}' : ' ');
buf.write(preStr.substring(cursor, cursor + 3));
cursor += 3;
}
} else {
if (decimalIndex != -1) {
buf.write(numStr.substring(0, decimalIndex));
} else {
buf.write(numStr);
}
}
// Decimal and post-decimal.
if (decimalIndex != -1) {
buf.write('.');
if (postCount > 4) {
// Insert a space after each grouping of 3.
buf.write(numStr.substring(decimalIndex + 1, decimalIndex + 4));
var cursor = 3;
while (cursor < postCount) {
buf
..write(unicode ? '\u{2009}' : ' ')
..write(numStr.substring(decimalIndex + 1 + cursor,
min(decimalIndex + 4 + cursor, numStr.length)));
cursor += 3;
}
} else {
buf.write(numStr.substring(decimalIndex + 1));
}
}
if (expIndex != -1) buf.write(str.substring(expIndex));
return buf.toString();
}