How could I extend a format-spec for existing type (eg float) in C++?

Advertisements

I want to extend formatting options for floating-point type, preferably preserving some of the existing options. For instance, I want to add a new type specifier for the measurements with units to write like this std::format({:.5mm}, 0.05f) and get my data printed with precision=5, but also multiplied by 1000 and prefixed with ‘mm’. Is that even possible?

>Solution :

The formatting specification for basic types like float are built into the system; you cannot extend them.

You can wrap them in a user-defined type which you can apply whatever formatting to you like. As exemplified in the comments, std::format("{:.5mm}", MyUnit(0.05f)), where MyUnit is your type which has its own formatting specification.

Leave a ReplyCancel reply