Last active
February 18, 2025 12:22
-
-
Save PlugFox/22aa280ffe2d847ca8c074b7eebca969 to your computer and use it in GitHub Desktop.
Format numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Format numbers | |
// https://dartpad.dev/?id=22aa280ffe2d847ca8c074b7eebca969 | |
import 'dart:math' as math; | |
String formatNumber$1(int number) => number.toString().replaceAllMapped( | |
RegExp(r'(\d)(?=(\d{3})+(?!\d))'), | |
(match) => '${match[1]} ', | |
); | |
String formatNumber$2(int number) { | |
if (number == 0) return '0'; | |
final isNegative = number.isNegative; | |
var temp = number.abs(); | |
final total = (math.log(temp) / math.log(1000)).floor() + 1; | |
final parts = List<String>.filled(total, '', growable: false); | |
for (var i = total - 1; i >= 0; i--) { | |
final chunk = (temp % 1000).toString(); | |
temp ~/= 1000; | |
parts[i] = temp > 0 ? chunk.padLeft(3, '0') : chunk; | |
} | |
final result = parts.join(' '); | |
return isNegative ? '-$result' : result; | |
} | |
String formatNumber$3(int number) { | |
final chars = | |
number.abs().toString().codeUnits.reversed.toList(growable: false); | |
final total = chars.length + (chars.length / 3).ceil(); | |
final buffer = List.filled(total, ' '.codeUnitAt(0), growable: false); | |
for (var i = 0, j = 0; i < chars.length; i++, j++) { | |
if ((i % 3) == 0) j++; | |
buffer[j] = chars[i]; | |
} | |
final result = String.fromCharCodes(buffer.reversed); | |
return number.isNegative ? '-$result' : result; | |
} | |
void main() { | |
final formatNumber = formatNumber$1; // $1 $2 $3 | |
print(formatNumber(12_123_123_123_123)); // 12 123 123 123 123 | |
print(formatNumber(1_234_567_890)); // 1 234 567 890 | |
print(formatNumber(1_000_000)); // 1 000 000 | |
print(formatNumber(-9_876_543)); // -9 876 543 | |
print(formatNumber(123)); // 123 | |
print(formatNumber(-12)); // -12 | |
print(formatNumber(-1_234)); // -1 234 | |
print(formatNumber(0)); // 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment