Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nicely formatting numbers in C++ [duplicate]

Tags:

c++

In Ada it is possible to write numbers with underscores for separating digits, which greatly improves readability. For example: 1_000_000 (which is equivalent to 1000000) Is there some similar way for C++?

EDIT: This is question about source code, not I/O.

like image 407
darkestkhan Avatar asked Apr 04 '13 15:04

darkestkhan


People also ask

Is %d for double in c?

%d stands for decimal and it expects an argument of type int (or some smaller signed integer type that then gets promoted). Floating-point types float and double both get passed the same way (promoted to double ) and both of them use %f .

Is %F for double?

"%f" is the (or at least one) correct format for a double. There is no format for a float , because if you attempt to pass a float to printf , it'll be promoted to double before printf receives it1.

Can we use %F for double in c?

We can print the double value using both %f and %lf format specifier because printf treats both float and double are same. So, we can use both %f and %lf to print a double value.

What is %d %f %s in c?

The first argument to printf is a string of identifiers. %s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0]. Follow this answer to receive notifications.


1 Answers

As of C++14, you can use ' as a digit group separator:

auto one_m = 1'000'000;

Previous versions of C++ did not support this natively. There were two major workarounds:

  • Using user-defined literals in C++11; this would allow you to write code as follows:

    auto x = "1_000_000"_i;
    

    (Writing this as a constexpr would be trickier – but is definitely possible.)

  • Using a straightforward macro, which would allow the following code:

      auto x = NUM(1,000,000);
    
like image 90
Konrad Rudolph Avatar answered Oct 01 '22 16:10

Konrad Rudolph