Search code examples
string-formattingd

Formatting a string in D


I read on D's documentation that it's possible to format strings with arguments as print statements, such as the following:

float x = 100 / 3.0;
writefln("Number: %.*g", 2, x);

Number: 33.33

However, I'm wondering how I would do this if I just wanted the string equivalent, without printing it. I've looked at the std.format library but that seems way to messy for something I only need to use once. Is there anything a little bit more clear available?


Solution

  • Import std.string or std.format and use the format function.

    import std.string;
    
    void main()
    {
        float x = 100 / 3.0;
        auto s = format("Number: %.*g", 4, x);
        assert(s == "Number: 33.33");
    }