3

I have a variable which is made up of a multiplication of 2 more variables

 var EstimatedTotal = GetNumeric(ServiceLevel) * GetNumeric(EstimatedCoreHours); 

Is it possible, and if so how, or what is the function called to format this as currency? I've been googling only I cant find a function and the only ways I've seen are really, really long winded

1

6 Answers 6

9

Taken from here: http://javascript.internet.com/forms/currency-format.html. I've used it and it works well.

function formatCurrency(num) { num = num.toString().replace(/\$|\,/g, ''); if (isNaN(num)) { num = "0"; } sign = (num == (num = Math.abs(num))); num = Math.floor(num * 100 + 0.50000000001); cents = num % 100; num = Math.floor(num / 100).toString(); if (cents < 10) { cents = "0" + cents; } for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) { num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3)); } return (((sign) ? '' : '-') + '$' + num + '.' + cents); } 
Sign up to request clarification or add additional context in comments.

Comments

9

If you are looking for a quick function which would format your number (for example: 1234.5678) to something like: $1234.57 you may use .toFixed(..) method:

EstimatedTotal = "$" + EstimatedTotal.toFixed(2); 

The toFixed function takes an integer value as the argument which means the number of trailing decimals. More information about this method can be found at http://www.w3schools.com/jsref/jsref_tofixed.asp.

Otherwise, if you would like to have your output format as: $1,234.57 you need to implement your own function for this. Below are two links with implementation:

Comments

3

How abt using jQuery globalization plugin from microsoft? https://github.com/nje/jquery-glob

Comments

2

May not be perfect, but works for me.

if (String.prototype.ToCurrencyFormat == null) String.prototype.ToCurrencyFormat = function() { if (isNaN(this * 1) == false) return "$" + (this * 1).toFixed(2); } 

Comments

0

There are no in-built functions for formatting currency in Javascript.

There are a number of scripts that you can find online that will help you with writing your own, however, here's one:

http://javascript.internet.com/forms/currency-format.html

Google "javascript currency".

Comments

0

Now there's Intl.NumberFormat that can easily format currency or other numbers to locales.

Using your EstimatedTotal example and USD, you can do:

const formattedTotal = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(EstimatedTotal)); 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.