when to use toString() method

In most languages, toString or the equivalent method just guarantees that an object can be represented textually. This is especially useful for logging, debugging, or any other circumstance where you need to be able to render any and every object you encounter as a string. Objects often implement custom toString behavior so that the method … Read more

How to ‘cout’ the correct number of decimal places of a double value?

Due to the fact the float and double are internally stored in binary, the literal 7.40200133400 actually stands for the number 7.40200133400000037653398976544849574565887451171875 …so how much precision do you really want? 🙂 #include <iomanip> int main() { double x = 7.40200133400; std::cout << std::setprecision(51) << x << “\n”; } And yes, this program really prints 7.40200133400000037653398976544849574565887451171875!

How does the .ToString() method work?

Sometimes when I call the ToString method it returns the fully qualified name of the runtime type of the object that received the call. Correct. But for some types, such as System.Int32, ToString returns the value of the receiver converted to a string. Correct. Does the System.Int32 struct override the ToString method? Yes. Do other … Read more

BigInteger to Hex/Decimal/Octal/Binary strings?

Convert BigInteger to decimal, hex, binary, octal string: Let’s start with a BigInteger value: BigInteger bigint = BigInteger.Parse(“123456789012345678901234567890”); Base 10 and Base 16 The built-in Base 10 (decimal) and base 16 (hexadecimal) conversions are easy: // Convert to base 10 (decimal): string base10 = bigint.ToString(); // Convert to base 16 (hexadecimal): string base16 = bigint.ToString(“X”); … Read more

Convert a vector to a string

Definitely not as elegant as Python, but nothing quite is as elegant as Python in C++. You could use a stringstream … #include <sstream> //… std::stringstream ss; for(size_t i = 0; i < v.size(); ++i) { if(i != 0) ss << “,”; ss << v[i]; } std::string s = ss.str(); You could also make use … Read more