2020 - Ensure costs are displayed in the format £X.XX

From TRCCompSci - AQA Computer Science
Jump to: navigation, search

The Issue

The monetary values in the skeleton program are displayed as decimals or integers. No currency symbol is displayed, and they often have more than 2 decimal places.

The Solution

You can pass a string format to the variable to format the text as a currency.

Example

The program uses the 'ToString()' function of a numeric variable, there are many instances of this in the skeleton program. The ToString function accepts parameters, these can be used to format the output. So find an example of 'ToString()', mine below is in the 'ProcessDayEnd' method in the Company class:

            details += "Previous balance for company: " + balance.ToString() + "\n";
            balance += profitLossFromOutlets - dailyCosts - deliveryCosts;
            details += "New balance for company: " + balance.ToString();

Now inside the () for the 'ToString' add "C2" , for example:

            details += "Previous balance for company: " + balance.ToString("C2") + "\n";
            balance += profitLossFromOutlets - dailyCosts - deliveryCosts;
            details += "New balance for company: " + balance.ToString("C2");

The 'C' means currency, and the 2 means 2 decimal places.