COMMUNITY

String formatting? (ex. ints, space-padded, width = 3)

I’d like to create strings that include ints and display them like:

  0 --   5
  5 --  10
 10 --  15
 ...
 95 -- 100

Given integers like those, how can I specify string formatting like “integers, take up 3 places, right-justified, padded with spaces”?

https://api.haxe.org/StringTools.html

StringTools.lpad for your particular example.

1 Like

StringTools.lpad() would do the trick:

using StringTools;

class Main {
	static function main() {
		for (_ in 0...10) {
			var a = Std.string(Math.floor(Math.random() * 500)).lpad(" ", 3);
			var b = Std.string(Math.floor(Math.random() * 500)).lpad(" ", 3);
			trace('$a -- $b');
		}
	}
}
source/Main.hx:8: 157 --  35
source/Main.hx:8: 369 -- 392
source/Main.hx:8: 324 -- 460
source/Main.hx:8:  96 --   2
source/Main.hx:8: 165 --  49
source/Main.hx:8: 373 -- 184
source/Main.hx:8: 367 -- 375
source/Main.hx:8: 262 --  24
source/Main.hx:8: 218 -- 421
source/Main.hx:8: 436 -- 408
1 Like

Offtopic: Math.floor(Math.random() * 500) is the same as Std.random(500) and '$value' (or "" + value) is usually faster than Std.string(value) for numeric types :wink:

2 Likes

What…

Because Std.string(value) generates a call, while "" + value on some targets is generated as-is and handled by the target platform.

Cool, thanks, all!

Ah, nice. Thanks!

Man, I’d love to see a pinned forum post collection of x is faster than y Haxe code samples.