Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Improving the Numerical Presentation

Listing 4 illustrates some simple ways of enhancing the data from Figures 1–3. As a first stab at improving the presentation, I just round up with the ceil() function and then round down with the floor() function.

Listing 4 Selective use of floor() and ceil() functions

Console::Write("Per person winnings: ");
Console::WriteLine(winnings/numOfPeople);
Console::Write("Per person winnings with cast: ");
Console::WriteLine(floor(static_cast<double>(winnings)/numOfPeople));
Console::Write("Per person winnings with incorrect cast: ");
Console::WriteLine(static_cast<double>(winnings/numOfPeople));
Console::Write("Per person winnings with old form of cast: ");
Console::WriteLine(ceil(double(winnings)/numOfPeople));

Figure 4 illustrates the program output from the code in Listing 4.

Figure 4

Figure 4 Casting and rounding up/down

Again, my problem is that I’m losing the fractional part.

Clearly, there will be many cases in which you have to retain and manipulate the fractional part. For this, the Decimal type is useful because it allows for calculations requiring large numbers of significant integral and fractional digits and no round-off errors. The Decimal keyword denotes a 128-bit data type, so it’s big! When compared with floating-point types, the Decimal type has greater precision and a smaller range, which makes it suitable for financial calculations.

Let’s take a quick look at the use of Decimal in Listing 5.

Listing 5 Manipulating currency values

Decimal winnings = 20000;
int numOfPeople = 3;
Decimal myWinnings = System::Decimal::Divide(winnings, Decimal(numOfPeople));
Console::Write("Per person winnings in currency format: ");
Console::WriteLine(myWinnings.ToString("C"));

In the third line of Listing 5, I allocate a variable (called myWinnings) of the Decimal type. In this line, I invoke the Divide() method to divide the winnings by the number of people in the syndicate. Notice that I explicitly cast to Decimal the variable numOfPeople. This is good practice, but not strictly necessary in this case.

In the last line of Listing 5, I call the ToString() method of the Decimal type. Passing the "C" string into this method renders the value as a currency amount—dollars in this case.

In Figure 5, the comma is added for the thousands, and the decimal point is added for the cents value. Finally, the value is rounded up. This is quite a lot of power for one line of code!

Figure 5

Figure 5 Using currency formats

C++ has many more facilities for numerical manipulation than those looked at here. The selections have been included as a basis for further exploration!

Let’s now move into the area of call-by-reference.

  • + Share This
  • 🔖 Save To Your Account