On Sunday, 15 March 2015 at 15:41:09 UTC, Darts wrote:
Hey, I'm just looking for how to turn some numbers into strings in particualr ways. Specifically, I want to force some ints (and maybe floats too) to give me a string that consists of exactly four numbers ( 3005, 0038, 0130, etc ). I'd also like to know how to format a float to give me only one decimal place. If there are ways to print out in hex or scientific notation I'd also like to know about those too!

    import std.stdio;
    int x = 42;
    writefln("int: %04d", x);
    float f = 3.14159;
    writefln("float: %.1f", f);
    writefln("hex: 0x%08x", x);

If you need to work with the string instead of printing it, use format():

    import std.string : format;
    // in not-yet released DMD 2.067
    // import std.format : format;
    // is also possible
    string s = format("%04d", 42);

Here's the explanation of the format strings:
http://dlang.org/phobos/std_format.html

Unfortunately the layout is broken at the moment. Anyway, if you're unfamiliar with format strings, it may be better to read one of the existing format string tutorials. Randomly picked one of the Google results:

http://www.cprogramming.com/tutorial/printf-format-strings.html

This one is about C's printf() function, but it's applicable to D, too, because format strings are almost identical in both languages.

Reply via email to