Skip to content

Commit 20a4e7c

Browse files
committed
added a function to format numbers into a truncated string format
1 parent ee20aac commit 20a4e7c

File tree

1 file changed

+33
-4
lines changed

1 file changed

+33
-4
lines changed

utils/misc.simba

Lines changed: 33 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ Example:
4747
function Level2XP(level: Integer): Integer;
4848
var
4949
total:Double;
50-
i:Int32;
50+
i:Integer;
5151
begin
5252
for i := 1 to level-1 do
5353
total += Floor(i + 300 * 2 ** (i / 7));
@@ -63,7 +63,7 @@ Converts XP to the respective level.
6363

6464
Example:
6565
```pascal
66-
WriteLn XP2Level(100000);
66+
WriteLn XP2Level(100000);
6767
```
6868
*)
6969
function XP2Level(xp: Integer): Integer;
@@ -78,6 +78,35 @@ begin
7878
end;
7979

8080

81+
(*
82+
## FormatNumber
83+
```pascal
84+
function FormatNumber(n: Double; dec: Byte = 3): String;
85+
```
86+
Truncates a number with a runescape like truncation.
87+
88+
Example:
89+
```pascal
90+
WriteLn FormatNumber(100000); //100k
91+
```
92+
*)
93+
function FormatNumber(n: Double; dec: Byte = 3): String;
94+
const
95+
SUFFIXES: TStringArray = ['', 'K', 'M', 'B', 'T'];
96+
var
97+
i: Integer;
98+
f: Double;
99+
begin
100+
if n = 0 then
101+
Exit('0');
102+
103+
i := Min(Trunc(Ln(Abs(n)) / Ln(1000)), 4);
104+
f := n / Power(1000, i);
105+
106+
Result := FormatFloat('0.' + StringOfChar('#', dec), f) + Suffixes[i];
107+
end;
108+
109+
81110
(*
82111
## TColor.Random
83112
```pascal
@@ -117,7 +146,7 @@ WriteLn arr.GetRarest();
117146
function TColorArray.GetRarest(): TColor;
118147
var
119148
weights: TIntegerArray;
120-
i,L : Int32;
149+
i,L : Integer;
121150
begin
122151
L := High(Self);
123152
if (L <= 0) then Exit;
@@ -174,7 +203,7 @@ end;
174203
//credits: Simba1400/Source/MML/simba.tpa.pas#L2440C10-L2440C21
175204
function TImage.ColorsInLine(start, stop: TPoint; colors: TIntegerArray): Boolean;
176205
var
177-
Xinc, YInc: Int32;
206+
Xinc, YInc: Integer;
178207
TwoDxAccumulatedError, TwoDyAccumulatedError: Integer;
179208
current, d, twoD: TPoint;
180209
begin

0 commit comments

Comments
 (0)