Skip to content

ui::DecimalFormatter

Header: winui/core/NumberFormat.hpp.

Formats and parses plain decimal numbers.

A plain value handed to NumberBoxControl::set_number_formatter() or ui::NumberBox::number_formatter. Unless symbols pins them, the separators follow the regional format at the time of each call, so the same formatter writes "1,5" in de-DE and "1.5" in en-US.

Example:

ui::DecimalFormatter dollars;
dollars.fraction_digits = 2;
dollars.rounder         = ui::IncrementNumberRounder{0.01, ui::RoundingAlgorithm::RoundHalfUp};

// The NumberBox shows 3 as "3.00" and reads what the user types back with the same formatter.
ui::Property<std::optional<double>> price{3.0};
window.set_content(ui::VerticalStack{
    .spacing = 8,
    .content = {
        ui::NumberBox{.header = "Price", .value = price, .min = 0.0, .number_formatter = dollars},
        ui::Text{.text = ui::bind(price, [dollars](const std::optional<double>& p) {
            return p ? "Three for $" + dollars.format(*p * 3.0) : std::string{};
        })},
    },
});

// Text from elsewhere, a CSV cell say, parses the same way; nullopt when it is not a number.
const std::optional<double> cell = dollars.parse(" 4.5 "); // 4.5

integer_digits

int integer_digits = 1

The fewest integer digits shown, padded with leading zeros.

fraction_digits

int fraction_digits = 0

The fewest fraction digits shown, padded with trailing zeros. More are shown when the value has them. Set rounder to limit them.

is_grouped

bool is_grouped = false

Groups the integer digits with the grouping separator, by default in threes with ,.

is_decimal_point_always_displayed

bool is_decimal_point_always_displayed = false

Shows the decimal point even with no fraction digits.

rounder

std::optional<IncrementNumberRounder> rounder {}

Rounds the value before formatting; unset formats it unrounded.

symbols

std::optional<NumberFormatSymbols> symbols {}

The separators. Unset follows regional_number_format(), the user's locale. NumberFormatSymbols::invariant() pins . and ,.

effective_symbols

const NumberFormatSymbols& effective_symbols() const

The separators this formatter writes and reads with: symbols, or the regional format.

format

std::string format(double value) const

value as text. NaN and the infinities format as "NaN", "∞" and "-∞".

parse

std::optional<double> parse(std::string_view text) const

Reads the whole of text, surrounding spaces aside, as one number written with the decimal separator. Grouping separators are allowed when is_grouped is set. Returns nullopt when text is not a number.