|
|
Title | Calculate escalating royalties |
Description | This example shows how to calculate escalating royalties in Visual Basic 6. |
Keywords | escalating royalties, royalties, calculate, percent, FormatCurrency, GetPercent, percent |
Categories | Algorithms, Strings |
|
|
This example calculates escalating royalties. For example, an author might earn 10 percent of price each on the first 2,000 copies sold, 12 percent on the next 2,000 copies, 15 percent on the next 2,000 copies, and 17 percent on any additional copies sold.
This program lets you enter the royalty percentages, the number of books at each royalty percentage, and book's price each (the net price the publisher receives per book), and the number of books sold. When you click the Calculate button, the following code executes.
The code gets the price each and number of copies sold. It then loops through the royalty levels. This example only allows four levels numbered 0 through 3.
For each level, the code gets the number of copies at that level. If the number possible is greater than the remaining number of books sold, it sets the number of copies equal to the remaining number of books.
The code uses the GetPercent function to get the royalty percentage for this level. It multiplies the number of copies at this level by the price each and the royalty percent to get the value of this level's royalties. The program uses FormatCurrency to display the amount in a label and subtracts the number of copies at this level from the remaining number of copies.
After it has calculated the royalties at each level, the code displays the total royalties in the label lblRoyaltyTotal.
|
|
Private Sub cmdCalculate_Click()
Dim price_each As Single
Dim royalty As Single
Dim num_copies As Long
Dim next_copies As Long
Dim next_royalty As Single
Dim i As Long
royalty = 0
price_each = CSng(txtPriceEach.Text)
num_copies = CLng(txtTotalCopies.Text)
For i = 0 To 3
' See how many copies we have at this level.
next_copies = CLng(txtCopies(i).Text)
If next_copies > num_copies Then next_copies = _
num_copies
' Calculate the royalty on these copies.
next_royalty = next_copies * price_each * _
GetPercent(txtRoyalty(i).Text)
royalty = royalty + next_royalty
lblRoyalty(i).Caption = FormatCurrency(next_royalty)
' Subtract from the total number of copies.
num_copies = num_copies - next_copies
Next i
lblRoyaltyTotal.Caption = FormatCurrency(royalty)
End Sub
|
|
Function GetPercent converts a string into a Single. If the string contains a percent sign, the function removes it and divides the number by 100. For example, it converts the string "10%" into 0.10.
|
|
' Convert a value that may have
' a % sign into a Single.
Private Function GetPercent(ByVal txt As String) As Single
' See if it contains a %.
If InStr(txt, "%") > -1 Then
' Divide by 100.
GetPercent = CSng(Replace(txt, "%", "") / 100)
Else
GetPercent = CSng(txt)
End If
End Function
|
|
|
|
|
|