banner



How To Use Money Notation In Cpp

Boost::format (and wformat) examples – numbers: int, float, double

Past , last updated June 27, 2019

Boost Format is a very versatile and easy to employ formatting library. If you're using Boost, and then at that place is no point in using other formatting libraries for formatting. For most uses, heave::format and boost::wformat are perfectly suitable.

Boost Format is not equally fast a sprintf and that family of formatters, but it is type rubber and robust. Information technology uses streams to construct the output, so there is no chance of buffer overflow and other nasal demons coming out of your olfactory organ. Co-ordinate to that table, Boost Spirit Karma is even faster. That's worthy a web log post in itself, simply this is about boost::format.

This is a continuation of the beginning boost format postal service, with more than images and descriptions.

Basic number formatting

I've used boost::format in many projects and it has an piece of cake syntax in one case y'all become to know it. Information technology has two types of formatting rules, i is printf-like formatting and the other is positional arguments (similar formatting in C#). I've never had a reason to utilise positional notation, however they are very similar to the print-like formatting rules and the reward is that you lot can switch the order of arguments during runtime (think i18n and language translation support).

Example with default floating betoken precision formatting

Formatting floating signal numbers is 1 of the near used features of string formatting. There aren't many other means of outputting floating point numbers than use formatting of some sort.

const double almostpi = 22.0 / vii.0;  // Printf printf("Pi is %fn", almostpi);  // Boost format with printf syntax boost::format printf_formatting("Pi is %fn"); std::cout << printf_formatting % almostpi;  // Boost format with positional syntax heave::format position_formatting("Pi is %1%n"); std::cout << position_formatting % almostpi;  // Output: // Pi is 3.142857 // Pi is iii.142857 // Pi is 3.14286

The archaic method printf is merely hither equally a comparison. It should not be used in new code equally this family of formatters is regarded unsafe.

Lets see what is happening here. The formatting rule %f tells the printf method to format a floating point number using default rules, which is about 6 decimal points.

Floating point replacement of %f

At %f the contents of the variable almostpi will be expanded and output into the standard output, which normally is the console window. The plan will output: Pi is iii.142857

There is actually nothing more than magic than that. The rest of the options are just variations of the aforementioned. Supplant a specific code with some contents.

The same diagram for heave::format with printf-fashion formatting rules.

Boost::format %f

Default formatting with a long floating point number

Formatting big numbers are similar to those small numbers.

const double almostpi = 22.0 / seven.0; const double distancetosun = 149600000000.0;    // meters const double earthorbitlength = 2 * almostpi * distancetosun;  // Printf printf("Earth orbit distance is %f metersn", earthorbitlength);  // Boost format with printf syntax boost::format printf_formatting("Earth orbit distance is %f metersn"); std::cout << printf_formatting % earthorbitlength;  // Boost format with positional syntax boost::format position_formatting("Earth orbit distance is %one% metersn"); std::cout << position_formatting % earthorbitlength;  // Output: // Earth orbit distance is 940342857142.857180 meters // World orbit distance is 940342857142.857180 meters // Earth orbit distance is 9.40343e+011 meters        

The default precision is still 6 decimal points, however the%1% formatter decided scientific notation was a better fit. More on that later.

Decision-making precision with floating point number format

The format specifier for old fashion print is "%[flags][width][.precision][length]specifier ".

The format specifier for heave format positional notation is: "%[N $][flags][width][. precision]type-char ".

Both formats are very similar, and there are simply a few actual differences between those two specifiers.

For most purposes, the default settings are sufficient when you lot force the blazon of the format, except when using the default%1% type. Information technology'll switch over to scientific notation effectually 6-seven characters length.

When formatting large numbers, the number will never be truncated. That determination is a trade-off between wanting to show the correct number or apply the correct formatting. It's easier to see the formatting is off, than to effigy out the number is missing some integers in 1 or other terminate in some printout.

// Printf printf("Pi is '%10.2f'n", almostpi);  // Boost format with printf syntax boost::format printf_formatting("Pi is '%10.2f'n"); std::cout << printf_formatting % almostpi;  // Boost format with positional syntax boost::format position_formatting("Pi is '%1$10.2f'n"); std::cout << position_formatting % almostpi;  // Output: // Pi is '      iii.14' // Pi is '      3.14' // Pi is '      iii.14'        

Format with precision

Numbers are non truncated when they overflow the width.

// Printf printf("Globe orbit distance is '%5.2f' metersn", earthorbitlength);  // Boost format with printf syntax heave::format printf_formatting("Globe orbit distance is '%5.2f' metersn"); std::cout << printf_formatting % earthorbitlength;  // Heave format with positional notation boost::format position_formatting("Earth orbit distance is '%one$v.2f' metersn"); std::cout << position_formatting % earthorbitlength;  // Output: // Earth orbit altitude is '940342857142.86' meters // Earth orbit distance is '940342857142.86' meters // Earth orbit distance is '940342857142.86' meters        

When scientific note becomes the default

At some point, the positional notation formatter will switch to scientific notation when you're not using whatever type specifiers. Here is a small test demonstrating when it volition switch from floating point representation and over to scientific notatation.

heave::format scinotation("Practice we utilise scientific? '%1%'n");  for (size_t n=0; north<xv; ++n) {     double value = 1 * pow(ten, northward) + 0.5;     std::cout << scinotation % value; }  // Output: // Do we use scientific? 'i.5' // Do we use scientific? 'ten.5' // Do nosotros use scientific? '100.v' // Do nosotros use scientific? 'chiliad.5' // Do we use scientific? '10000.5' // Do we use scientific? '100001' // Do we use scientific? '1e+006' // Do we utilise scientific? '1e+007' // Exercise nosotros employ scientific? '1e+008' // Exercise we employ scientific? '1e+009' // Practise nosotros use scientific? '1e+010' // Practice we use scientific? '1e+011' // Do nosotros use scientific? '1e+012' // Practice we utilize scientific? '1e+013' // Do nosotros use scientific? '1e+014'        

Using heave::wformat for i18n (Internationalization)

Here is a cursory example on how to use the positional note for translations with wformat.

// Language string input parameters // one - Title // 2 - Given name // iii - Family proper noun  std::wstring english = 50"Hello, %one% %3%, %two%n"; std::wstring norwegian = Fifty"Hei %2% %3%due north"; std::wstring russian = L"здравствуйте %two% %3%";  std::wstring title = L"Mr."; std::wstring name = 50"John"; std::wstring family unit = L"Doe";  std::wcout << "English: " << boost::wformat(english language) % championship % proper name % family unit; std::wcout << "Norwegian: " << boost::wformat(norwegian) % title % proper name % family; std::wcout << "Russian: " << boost::wformat(russian) % championship % name % family;  // Output: // English: Hello, Mr.Doe, John // Norwegian: Hei John Doe // Russian: здравствуйте John Doe        

The thought is that for each cord requiring formatting, there must be a predefined ready of keys. In this example, all three (title, name, family name) is given into the boost::wformat object, only merely the necessary parameters are used. This is (almost) impossible with the printf-family.

With positional notation, it'due south fully supported to utilise a dissimilar order than the order of parameters.

Read as well: Boost format examples: dates, time, alignment, loops.
String format

Why is the printf-family of formatters considered dangerous?

This is a very basic example on how easy it is to corrupt data on the stack with printf / sprintf. Due to how unlike compilers and runtimes do things, the consequence is undefined. It might format your computer, but most times this line volition corrupt the stack space and hopefully crash with a meaningful message. Visual Studio will ordinarily detect stack space abuse during debug, since it uses canaries around variables which is set up to a certain value (also known equally no-mans-land). If the value is not equally expected, an assert will trigger and notify the debugger there are problems.

char important[ten] = {0};	// Initialize to nulls char characters[10] = {0};	// Initialize to nulls char important2[10] = {0};	// Initialize to nulls  sprintf(characters, "Overflow '%v.2f'", almostpi);  // At this point, the stack space should be corrupted effectually 'characters'        

With Visual Studio, you'll ordinarily get this warning if you're in debug mode.

Comments

You may use these HTML tags and attributes: <a href="" title=""> <abbr championship=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Source: https://studiofreya.com/cpp/boost/boostformat-and-wformat-examples-numbers-int-float-double/

Posted by: michaelslanxim.blogspot.com

0 Response to "How To Use Money Notation In Cpp"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel