ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

ActionScript Financial Math Utility Class Library | Business Math | ActionScript

Updated on December 3, 2011

Many business applications require math operations as part of their normal use cases. To answer this recurring need, I have written an ActionScript utility class that includes many common business math equations like: compound interest, month loan payment calculator, how to calculate interest on a loan, a percentage of a number, variance, cost of goods sold (COGS), Gross Margin and many others.

The class is not exhaustive and it is a work in progress. That said I am sharing this utility class with the development community. I will continue to add new methods as time goes on. Any suggestions are always welcome.

If you would like to use the class, my only requirement is that the copyright notice and license remain intact in the source code.

Function Library

The NumberOfPayments function determines the amount of payment that are required to pay back an amount of money.

PaymentSchedule: The possible choices are: Bi-Weekly (every two weeks, or 2.3 times a month), Bi-Monthly (twice a month), Monthly (once a month).
TermOfLoan: How long in years is the length of the loan.

Return:The Number of payments

The monthly payment of the loan or amount of money to be repaid which includes the principal and interest.

Principal: The initial amount of the loan
Interest: The amount of interest expressed as a decimal. Ex. 2.0, 3.75. TermLoan:The length of loan in year(s);

Return:The loan payment amount.

This function determines how much interest a user will pay each month.

AnnualInterestRate: The amount of interest, say 3.5 that is charge on an annual basis

The monthly interest.

NumberOfDays calculates the difference between two random dates.

StartDate: The beginning date
EndDate: The final data

The number of days as an integer between the two dates.

CompoundInterest determines how much a certain amount of money will be worth after a period of time.

Principal: The initial amount to invest.
Interest: The rate of interest that the Principal will be invested at.
Period: The amount of time that the compounding interest will returned: Monthly, Quarterly, Yearly.
Years: The amount of years that Principal for.

The compounded interest fro the chosen period.

This function calculates the percentage of a number

Percentage: The percentage needed for a targetNumber.
TargetNumber: The number fr which the percentage will be calculated.

The percentage as a decimal

Similar as the previous function, except the return value is a number

Percentage: The percentage value to be applied to the number.
TargetNumber: The number that the percentage will calculate

Return: The number of the percentage value

This function will calculate the variance as a percentage between two values.

FirstAmount: The final amount.
SecondAmount: The initial amount.

Return: The variance as a percentage.

As above except the return variance value is returned as a number

FirstAmount: The final amount.
SecondAmount: The initial amount.

Return: The variance as a number

This function calculates the Gross Margin Return On Inventory or Gross Margin On Inventory Investment (GMROI or GMROII). This applied to retail operations where each dollar of revenue of a sellers inventory sold.

AverageInventoryValueAtCost: The value of the inventory at cost.
GrossMargin: The Gross Margin.

The ratio of the number of times Gross Margin is earned on inventory.

The Gross Margin is the profit earned between sales and cost.

TotalSales: The total sales at the end of a period of time.
MaterialCost: The cost of the material that were purchased and used to make the product.
LabourCost: The cost of the labour that was spent to produce the product.
OverheadCost: The amount of money in equipment, building, utilities that was spent and used to produce the product.

The Gross Margin on the sales of a product.

COGS is the Cost Of Goods Sold. Basically this function calculate the total value of an inventory at the close of a selling period.

OpeningInventoryValue: The value of the inventory at the start of a selling period.
PurchasesInPeriod: The total amount of new inventory purchased during the period.
ClosingInventoryInPeriod: The remaining inventory value at the end of a selling period.

The gross value of the inventory at the end of the selling period.

The materialCostOfGoogs calculates the total cost of the materials that were sold for a given selling cycle, example in the last 24 hours. It is measured by multiplying the quantity sold by the material cost per unit.

QuantitySold: This is the total quantities of products that were sold in a given selling period.
MaterialCostPerUnit: The material cost is the cost for one unit or product.

Total material cost for the quantity of products sold in a given period; 24 hours, a week, month, quarter or year.

The labourCostOfGoods is the amount labour that is used to produce one product or unit. If the product is purchased there wouldn’t be any labour cost.

QuantitySold: The total amount of products sold in a given period.
labourCostPerUnit: The cost of labour used to produce one product or unit.

The total cost of the labour used to produce a product.

This function calculates the total amount of overhead that was needed to produce the products that were sold.

QuantitySold: The total amount of products sold in a given period.
overheadCostPerUnit: The amount of overhead that was spent to produce one product.

The total amount of overhead that was spent to produce the products sold.

Conversion Costs is the total cost of the direct labour and overhead to produce one product. This function calculates the total conversion cost to produce the products that were sold.

quantitySold: Total amount of products sold.
labourCostPerUnit: The cost of direct labour needed to product one product.
overheadCostPerUnit: The cost of overhead to manufacture one product.

The total conversion cost spent to manufacture the sold products.


package com.kcodebook.apps.math
	import flash.display.Sprite;
	 * Copyright 2011 kCodebook Software
	 * FinanceMath Class designed and developed by Kevin Languedoc
	 * The FinanceMath class can be used "as is" in both commercial, personal or educational
	 * development projects free as long as the current copyright notice remains intact and well 
	 * as this license. Furthermore, the FinanceMath class can be included in Open Source
	 * projects without alteration as long as the included copyright notice remains intact within 
	 * this class file.
	 * Version 1.0  
	 * */
	public class FinanceMath extends Sprite
		public function FinanceMath()
		public var nbrPeriods:Number;
		public var balance:Number;
		public var growthRate:Number;
		public var compoundFrequency:Number;
		public var interestRate:Number;
		public var effectiveInterestRate:Number;
		public var nominalInterstRate:Number;
		public var periodicPayment:Number;
		public var futureValue:Number;
		public var presentValue:Number;
		public var cashFlow:Number;
		public var nthPeriod:Number;
		public const monthPeriod:String = 'Monthly';
		public const biMonthPeriod:String = 'Bi-Monthly';
		public const biWeeklyPeriod:String = 'Bi-Weekly';
		public const quarterlyPeriod:String = 'Quarterly';
		public const annuallyPeriod:String = 'Annually';
		private const nominalValue:int = 1
		public function NumberOfPayments(PaymentSchedule:String, TermInYears:int):Number
			var NbrPayments:int;
				case monthPeriod:
					NbrPayments = 12 * TermInYears
				case biMonthPeriod:
					NbrPayments = 24 * TermInYears;
				case biWeeklyPeriod:
					NbrPayments = 26 * TermInYears;
			return NbrPayments;
		public function MonthlyLoanPayment(principalAmount:Number, interest:Number, LoanTerm:Number):Number
			var monthlyPayment:Number=0;
			monthlyPayment = principalAmount * (MonthlyInterestRate(interest) + (MonthlyInterestRate(interest) / (((1+MonthlyInterestRate(interest))* Math.exp(12*LoanTerm))-1)));
			return monthlyPayment;
		public function MonthlyInterestRate(annualInterestRate:Number):Number
			var monthlyIRate:Number;
			monthlyIRate = (annualInterestRate/100)/12;
			return monthlyIRate;
		public function NumberOfDays(startDate:Date, endDate:Date):Number
			var NbrOfDays:Number = endDate.milliseconds - startDate.milliseconds;
			NbrOfDays = NbrOfDays / 1000;
			return NbrOfDays;
		public function CompoundInterest(principal:Number, years:Number, interetRate:Number, period:String):Number
			var compoundedAmount:Number;
					case monthPeriod:
						compoundedAmount = (principal*(nominalValue+(interetRate/100)))/12;
					case annuallyPeriod:
						compoundedAmount = (principal*(nominalValue+(interetRate/100)))*years;
					case quarterlyPeriod:
						compoundedAmount = (principal*(nominalValue+(interetRate/100)))/4;
				return compoundedAmount;
		public function percentAsDecimal(percent:Number, targetNumber:Number):Number
			var percentageAsDecimal:Number;
			percentageAsDecimal = (percent /100)*targetNumber;
			return percentageAsDecimal;
		public function percentAsNumber(percent:Number, targetNumber:Number):Number
			var percentageAsDecimal:Number;
			percentageAsDecimal = ((percent /100)*targetNumber)*100;
			return percentageAsDecimal;
		public function percentageVarianceDecimal(firstAmount:Number, secondAmount:Number):Number
			var variance:Number;
			variance = (firstAmount-secondAmount)/firstAmount;
			return variance;
		public function percentageVarianceNumber(firstAmount:Number, secondAmount:Number):Number
			var variance:Number;
			variance = ((firstAmount-secondAmount)/firstAmount)*100;
			return variance;
		public function calculateGMROI(averageInventoryValueAtCost:Number, GrossMargin:Number):Number
			var gmroii:Number;
			gmroii = GrossMargin / averageInventoryValueAtCost;
			return gmroii;
		public function grossMargin(totalSales:Number, materialCost:Number, labourCost:Number, overheadCost:Number, quantity:Number):Number
			var gmValue:Number;
			gmValue = totalSales - ((quantity * materialCost) - (labourCost+overheadCost));
			return gmValue;
		public function calculateInventoryCOGS(openingInventoryValue:Number, purchasesInPeriod:Number, closingInventoryValue:Number):Number
			var inventoryCogs:Number;
			inventoryCogs = (openingInventoryValue + purchasesInPeriod) - closingInventoryValue;
			return inventoryCogs;
		public function materialCostOfGoods(quantitySold:Number, materialCostPerUnit:Number):Number
			var materialCost:Number;
			materialCost = quantitySold * materialCostPerUnit;
			return materialCost;
		public function labourCostOfGoods(quantitySold:Number, labourCostPerUnit:Number):Number
			var labourCost:Number;
			labourCost = quantitySold * labourCostPerUnit;
			return labourCost;
		public function overheadCostOfGoods(quantitySold:Number, overheadCostPerUnit:Number):Number
			var overheadCost:Number;
			overheadCost = quantitySold * overheadCostPerUnit;
			return overheadCost;
		public function conversionCostOfGoods(quantitySold:Number, labourCostPerUnit:Number,overheadCostPerUnit:Number ):Number
			var conversionCost:Number;
			conversionCost = quantitySold * (labourCostPerUnit+overheadCostPerUnit);
			return conversionCost;

This library although fairly extensive is still a work in progress. More functions will be added in later versions. Also the functions may be re-organized into separate packages to better group related functions per business activity. You may download the source code from the Google Code web site: FinanceMath


    0 of 8192 characters used
    Post Comment

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      6 years ago from Canada

      Please note: I added a bug fix to the MonthLoanPayments function. The source code has been upload to the project page at Google Code

    • klanguedoc profile imageAUTHOR

      Kevin Languedoc 

      6 years ago from Canada

      Thanks :). Writing is definitely more fun than accounting. That is what is so much fun about writing, you don't have to get bogged down with the numbers. I hope the code is useful for someone.

    • JT Walters profile image

      JT Walters 

      6 years ago from Florida

      Hi klanguedoc,

      Really fascinating hub but I am having flashback to my accounting days.




    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)