2. Numbers

Checking Whether a String Is a Valid Number

#include <boost/regex.hpp>
#include <string>

std::string s("335635f");
boost::regex pattern("PATTERN");        // pattern given as a string-literal

if (boost::regex_match(s.begin(), s.end(), pattern)) {
        // string completely matches pattern
} else {
        // string does not match the pattern
// #---------------------------------
// Some PATTERNs in strings, escaped
// has nondigits                if     "\\D*"
// not a natural number"        unless "^\\d+$"             // rejects -3
// not an integer               unless "^-?\\d+$"           // rejects +3
// not an integer               unless "^[+-]?\\d+$"
// not a decimal number         unless "^-?\\d+\\.?\\d*$"     // rejects .2
// not a decimal number         unless "^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)$"

// A search of pattern in string is also possible.

Comparing Floating-Point Numbers

#include <sstream>
#include <iomanip>

 * equal(float num1, float num2, int accuracy) : returns true if
 * num1 and num2 are equal to accuracy number of decimal places
bool equal(float num1, float num2, int accuracy) {
        std::stringstream s1, s2;
        // write num1 to s1, represented with as many digits
        // in the fraction part (fixed) as specified by the precision
        s1 << std::fixed << std::setprecision(accuracy) << num1;
        s2 << std::fixed << std::setprecision(accuracy) << num2;
        return s1.str() == s2.str();
// The approach of fcomparing formatted strings is not the most efficient.

Rounding Floating-Point Numbers

Converting Between Binary and Decimal

Operating on a Series of Integers

Working with Roman Numerals

Generating Random Numbers

Generating Different Random Numbers

Making Numbers Even More Random

Generating Biased Random Numbers

Doing Trigonometry in Degrees, not Radians

Calculating More Trigonometric Functions

Taking Logarithms

Multiplying Matrices

Using Complex Numbers

Converting Between Octal and Hexadecimal

Putting Commas in Numbers

Printing Correct Plurals

Program: Calculating Prime Factors