Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format floating point numbers with decimal comma using the fmt library?

Tags:

c++

fmt

I want to use the fmt library to format floating point numbers.

I try to format a floating point number with decimal separator ',' and tried this without success:

#include <iostream>
#include <fmt/format.h>
#include <fmt/locale.h>

struct numpunct : std::numpunct<char> {
  protected:    
    char do_decimal_point() const override
    {
        return ',';
    }
};

int main(void) {
    std::locale loc;
    std::locale l(loc, new numpunct());
    std::cout << fmt::format(l, "{0:f}", 1.234567);
}

Output is 1.234567. I would like 1,234567

Update:

I browsed the source of the fmt library and think that the decimal separator is hard coded for floating point numbers and does not respect the current locale.

I just opened an issue in the fmt library

like image 820
schoetbi Avatar asked Jul 03 '19 06:07

schoetbi


People also ask

What is FMT in coding?

fmt stands for the Format package. This package allows to format basic strings, values, or anything and print them or collect user input from the console, or write into a file using a writer or even print customized fancy error messages. This package is all about formatting input and output.

How do you format a float?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.


1 Answers

The fmt library made the decision that passing a locale as first argument is for overwriting the global locale for this call only. It is not applied to arguments with the f format specifier by design.

To format floating point number using locale settings the format specifier L has to be used, for example:

std::locale loc(std::locale(), new numpunct());
std::cout << fmt::format(loc, "{0:L}", 1.234567);

The L format specifier supports floating-point arguments as of revision 1d3e3d.

like image 154
schoetbi Avatar answered Sep 30 '22 04:09

schoetbi