I am using Globalizejs to format Currency based on Logged-In user details in my application.
I don't want currency Symbol to be displayed when formatting is done using below code snippet:
Globalize.locale( "en" );
currencyFormatter = Globalize.currencyFormatter( "USD", {
maximumFractionDigits: 0,
});
currencyFormatter(parseInt(totalCost.amount));
which returns
$1,212,122,112 for amount: 1212122112
Is there any option similar to maximumFractionDigits to avoid the currency symbol ?
Short answer: Globalize.numberFormatter
Longer answer: Two benefits of using currency formatter is: (a) have the currency symbol properly formatted, and (b) have the appropriate number of fraction digits properly formatted; note that several currencies such as USD, EUR, have 2 fraction digits by default, but others like JPY have 0, there are different cases too.
The appropriate solution to customize the markup and style of a formatted output is to use parts Globalize.currencyToPartsFormatter: At the time we speak, this feature isn't implemented yet https://github.com/globalizejs/globalize/issues/679.
As a workaround, which should work fine for your specific use case (no currency symbol + integers only amount), using Globalize.numberFormatter should suffice.
Related
I have a script for taking data entered into a Price field on my editor and splitting it across a Pounds and Pence field based on the . symbol.
Now I've been asked if I could multiply the Price field by 1.2 and display the result in the Pounds field. The pence field would no longer be needed.
I have no idea if multiplication can even work and especially using decimal points... Can anyone explain how I should rewrite the below?
$('#price1').keyup(function(event) {
if ($('#price1').val().indexOf('.') != -1){
$('#pence1').val($('#price1').val().substr($('#price1').val().indexOf('.') + 1, $('#price1').val().lengh));
$('#pound1').val($('#price1').val().substr(0, $('#price1').val().indexOf('.')));
}else{
$('#pound1').val($('#price1').val());
};
});
Some things to remark:
Your current solution has a spelling mistake for length.
Don't locate the decimal point. Instead use native JavaScript capabilities to evaluate the input. You can use parseFloat(), Number() or the unary plus operator for that.
Once you have the numeric value, you can multiply using the * operator. As multiplication will also convert its operands to number, you don't even need the previous advice, although it is still good practice to first do the conversion to number and then do the arithmetic.
Use the input event instead of the keyup event: input is not always the result of key events (think copy/paste via context menu, drag/drop, other devices...)
Here is the proposed solution:
$('#price1').on("input", function(event) {
var num = +$('#price1').val(); // convert to number using unary plus operator
// multiply, format as string with 2 decimals, and convert back to number
num = +(num * 1.2).toFixed(2)
$('#pound1').val(num); // output
});
I have a string below that is a price in £, I want to remove the currency symbol and then convert this into a number/price I can use to compare against another value (eg. X >= Y ...)
£14.50
I have previously converted strings to numbers used for currency with
var priceNum = parseFloat(price);
IDEAL OUTCOME
14.50 as a number value. Can this be done in a single line?
I found this very helpful
var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9\.-]+/g,""));
Convert (Currency) String to Float
If the currency symbol will always be there, just use substring:
var priceNum = parseFloat(price.substring(1));
If it may or may not be there, you could use replace to remove it:
var priceNum = parseFloat(price.replace(/£/g, ""));
Beware that parseFloat("") is 0. If you don't want 0 for an empty input string, you'll need to handle that. This answer has a rundown of the various way to convert strings to numbers in JavaScript and what they do in various situations.
Side note: Using JavaScript's standard numbers for currency information is generally not best practice, because if things like the classic 0.1 + 0.2 issue (the result is 0.30000000000000004, not 0.3). There are various libraries to help, and BigInt is coming to JavaScript as well (it's a Stage 3 proposal at the moment, currently shipping in Chrome). BigInt is useful because you can use multiples of your basic currency (for instance, * 100 for pounds and pence).
try this number-formatter-npm library. This library is fantastic.
npm i number-formatter-npm
documentation:https://www.npmjs.com/package/number-formatter-npm
I have to display a number in currency format using the country code with comma and period separators based on the country.
Example if the number is 4294967295000 then
USA = USD 4,294,967,295,000.00
INDIA = INR 42,94,96,72,95,000.00
I got it working for India, but for USA I am getting this string but I need space between currency code and number:
var number = 4294967295000;
console.log(number.toLocaleString('en-IN', {
style: 'currency', currency: 'INR', currencyDisplay: 'code'
})); // INR 42,94,96,72,95,000.00
console.log(number.toLocaleString('en-US', {
style: 'currency', currency: 'USD', currencyDisplay: 'code'
})); // USD4,294,967,295,000.00
How do I achieve spacing between "USD" and number? I did not see anyting in option parameter regarding space. I can write custom code to add space, but I am trying to see if there is better option for doing the same.
I did not see anyting in option parameter regarding space.
So I set off down the rabbit hole.
When you pass options in to toLocaleString, it follows a number of steps. Firstly, it converts your passed in options to a NumberFormat object. It goes through a series of steps to do so, one of which is:
If s is "currency", then
a. Let c be converting c to upper case as specified in 6.1.
b. Set numberFormat.[[currency]] to c.
That means that whatever you've passed in as the currency option, so long as it's a proper currency code, is converted to uppercase and stored in the internal currency property on the NumberFormat object.
We then see that there are some other internal properties used on a NumberFormat - in this case, specifically the positivePattern internal slot. The spec notes:
The value of these properties must be string values that contain a substring "{number}"; the values within the currency property must also contain a substring "{currency}". The pattern strings must not contain any characters in the General Category “Number, decimal digit" as specified by the Unicode Standard.
IE note that at this point, for a given culture, we've created an object that effectively has a formatting string along the lines of {currency} {number}. Only in Chrome's (at least) case for USD, it is {currency}{number}. Note that in IE and Edge, you get the space after USD, so it's decided on a formatting string of {currency} {number}.
Next up, we get to the actual implementation of formatting the number. Step 7 says:
If the value of the numberFormat.[[style]] is "currency", then
a. Let currency be the value of numberFormat.[[currency]].
b. If numberFormat.[[currencyDisplay]] is "code", then
i. Let cd be currency.
c. Else, if numberFormat.[[currencyDisplay]] is "symbol", then
i. Let cd be an ILD string representing currency in short form. If the implementation does not have such a representation of currency, then use currency itself.
d. Else, if numberFormat.[[currencyDisplay]] is "name", then
i. Let cd be an ILD string representing currency in long form. If the implementation does not have such a representation of currency, then use currency itself.
e. Replace the substring "{currency}" within result with cd.
emphasis mine, showing the steps taken in this case.
TL;DR - this behaviour appears to browser dependent, and you'll need to parse and fix the resulting string yourself if you consistently want the space, there's no built-in way to do so.
If it's a reliable pattern that what you want to fix is a three-letter code followed by a digit, and you want to fix that by inserting a space, you could use this regex like this:
currencyStr = currencyStr.replace(/^([A-Z]{3})(\d)/, (match, $1, $2) => $1 + ' ' + $2);
I am trying to format the output of monetary values with moment JS, and using the example on their website '$ 0,0[.]00' and editing this for pound sterling '£ 0,0[.]00' only outputs the value, and not the pound sign.
Does numeral not support currencies other than dollars?
The code I am using is:
numeral(200).format('£ 0,0[.]00')
At lines 67 and 68 of the un–minified code there is:
// figure out what kind of format we are dealing with
if (format.indexOf('$') > -1) { // currency!!!!!
So yes, it seems "$" is the only currency symbol recognised. You can add the currency symbol separately, e.g.:
var amount = '£' + numeral(2456.01231).format('0,0[.]00');
console.log(amount); // £2,456.01
or extend the library to deal with other currency symbols.
It may be better to use the ISO symbol GBP, which is not ambiguous. There are many currencies that use the £ symbol, as there are many that use $.
Import the locale and then set it manually.
import numeral from 'numeral';
import 'numeral/locales/en-gb';
numeral.locale('en-gb');
numeral('1234.56').format('$0,0.00'); // £1,234.56
Bearing in mind this was originally answered over two years ago, I want to provide an alternative answer. Numeral now supports locales, meaning you can select different currency formats.
What I've done in my code base is:
Import numeral and require the GB locale
Define a default format using the GB locale
Use numeral(value).format() to apply the default formatting I've just defined
This is what it looks like:
import * as numeral from 'numeral';
require('numeral/locales/en-gb');
numeral.locale('en-gb');
numeral.defaultFormat('$0,0.00');
numeral(200).format(); // £200.00
numeral(1234).format(); // £1,234.00
numeral(5431.31).format(); // £5,431.31
Note: When specifying numeral.defaultFormat('$0,0.00') you still need to use a dollar sign. Because of the GB locale, though, numeral will actually render a £ instead. Using '£0,0.00' as a format won't actually render any currency sign.
I've figured out in the past that if I want a number 100000 to have commas then I just add .toLocaleString() to the angularJS variable. ie:
<span>{{variable.toLocaleString()}}</span>
Also, if want to limit the number of decimal places to a number 20.34343434 to lets say 2, then I would just add .toFixed(2). ie:
<span>{{variable.toFixed(2)}}</span>
Now I would like to do both. ie:
<span>{{variable.toFixed(2).toLocaleString()}}</span>
or
<span>{{variable.toLocaleString().toFixed(2)}}</span>
but neither seem to work. Maybe the solution to this has nothing to do with either function.
Question: How do I add commas and limit the amount of decimal places in a value using HTML and angularJS?
You can do this with a currency filter using an empty string for the currency symbol:
{{variable | currency:""}}
If you want to change the number of decimal places, you can specify it as an argument (default is 2):
{{variable | currency:"":3}}
If you insist on using function then you can use:
{{variable.toLocaleString("nu", {minimumFractionDigits: 2, maximumFractionDigits: 2})}}
This will take care of both commas/spaces (depending on locale) in integer digits as well as separator (. or ,) depending on locale.