Currency Script Calculation Woes

cornflakes_01
Tera Contributor

I'm currently doing a customization on the request items table that is making me pull out my hair. What I need to do is create a "Total Cost" field on the requested items table such that the field takes the price of the item, and multiplies that to give the total cost for that request item. The reason I need to do this is because we do our reporting at the request item level rather than at the request level. We've got some custom categories defined for request items such that we can report on items such as "We spent X amount of dollars on networking equipment, and X amount of dollars on server equipment".

The problem is, we're using a multi currency model, and all calculations are being done in the native instance currency. I've read over the wiki about doing scripting on price fields, but what i've got so far will not work for items that are in a currency other than canadian. I tried creating a calculated field, but that returns the wrong amount if the person viewing the record is in a different currency than that of the item. Our instance is defaulted to the Canadian Currency, and as such when i run the script below it converts the price into canadian, then takes that price, multiplies it by the quantity, and updates the u_total_price field with the new value. The problem is, i'm not sure how to convert that canadian result back into the currency that the item is defined in.

My test case is, if I have an item worth $1000USD, with 2 quantity, the script runs, and sets the u_total_price field to $2,054.84USD. The real result should be $2000USD.

My current business rule:
Type: onBefore
Conditions: current.quantity.changes() || current.price.changes()

Script:
updatePrice();

function updatePrice(){

var currency = current.price.getCurrencyString();

var abbCurrency = currency.slice(0,3);
var cost = parseFloat(current.price.getReferenceValue()) * current.quantity;
current.u_total_price = abbCurrency + ";" + cost;

}

I can understand why it is putting in the wrong amount, but how do I go about converting it back into the proper currency on the result's way back into the currency field?

Also, if i'm overcomplicating the problem, simpler ideas are definately welcome!

5 REPLIES 5

SaschaWildgrube
ServiceNow Employee
ServiceNow Employee

DevTools is a scoped application with many helpful scripts ready to be re-used.

The built-in currency conversion API object (GlideCurrencyConverter) is a bit tricky to use.

Here you can find a nice wrapper function for currency conversion based on the ServiceNow OOTB functionality:

https://github.com/saschawildgrube/servicenow-devtools/blob/master/update/sys_script_include_6f29745...