Numeral.js - is there no support of pound sterling? - javascript

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.

Related

Parsefloat with dot seperator

I have different numbers from 100.000 to 3.000.000 saved as a String. I Want to convert them into a number in exact the same format with the parsefloat function and sum them after it. With numbers under 1 million and only one dot it will working, with a number over one million it deletes the last numbers after the dot. for example when the productionItem.calculationResult.stromKwh = 1.358.149 the result it 1.358.
result is 1358.149 parseFloat(String(productionItem.calculationResult.stromKwh).replace('.','').replace(',','.'));
result is 1.358
parseFloat(String(productionItem.calculationResult.stromKwh).replace(',','.'));
First of all you need to understand that different locales use different number formatting characters. In english locales, decimals are separated using a dot (3.14159265) and thousands are separated using commas (1,000,000 is a million).
In german locales, these are reversed. Your numbers are formatted according to german locale rules.
Programming languages almost always use english locale conventions but without thousands separators. The dot is interpreted as the decimal point. parsefloat() parses numbers as JavaScript would do it, using the dot as the decimals separator.
Sadly, JavaScript has locale-specific number formatting (toLocaleString()) but no corresponding parsing functions. There are libraries which provide these, have a look at How do I convert String to Number according to locale (opposite of .toLocaleString)? for a discussion.

Remove currency symbol from string and convert to a number using a single line in Javascript

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

Converting Numbers from French Locale to English Locale JavaScript

I have a list of number like "123,459","561,79" from france region and I want to convert it into our normal US english numbering system. How can I do it in JS using locale?
function eArabic(x){
return x.toLocaleString('en-US',{ minimumFractionDigits:2,
maximumFractionDigits:2 });
}
Input : "123,345"
Output : "123,345"
Expected Output : 123.345
This doesn't looks good. Do you have any suggestion for this problem? I do not want to replace comma with '.' in order to solve this issue.
You’re passing in a string, not a Number object (which is what toLocaleString requires to produce a formatted number). Do you have the original number available?
If you don’t, then your best bet (assuming a standardised format for the original number strings) would be to convert them into normal numbers then reformat them. Assuming that your numbers are going to be formatted according to French standards (, as a decimal separator) then you could use a simple string replacement before creating your number object:
var frenchNumberString = '123,456';
var numberObject = new Number(frenchNumberString.replace(',', '.'));
Then pass numberObject into your formatting code.

How to remove currency symbol, when formatting currency using Globalizejs library?

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.

Adding a prefix and commas in a Javascript counter

I have a javascript counter that I want to add a dollar sign "$" to the front of and I'd like for there to be commas to help with legibility as the counter climbs to 3,000,000.
The counter is a part of a template module (windy-counter). Here is the code from the page the counter is displaying on:
<div class ="windy-counter" ##>[zt_counter_box iconSize="14" from="0" to="3000000" unit="+" unitPos="after" updown="up" speed="3000" countColor="#00aeef" contentColor="#747474" border="no" bdColor="#e0dede" column="3"]Operating Costs Saved[/zt_counter_box]</div>
Not sure if I can achieve this here or if I need to dive in to the Java code?
if you are trying to convert a number in javascript to a formatted string as you posted then you can make use of toLocaleString function and then append $ at the beginning.
formattedNumber = "$" + num.toLocaleString();
Complete Code:
var num = 3000000;
formattedNumber = "$" + num.toLocaleString();
console.log(formattedNumber);
// OR
var num = 3000000;
formattedNumber = num.toLocaleString('en-US', {style: 'currency', currency: 'USD'});
console.log(formattedNumber);
Perhaps the simplest solution would be if toLocaleString could be combined with toFixed, but that doesn't seem practical.
toLocaleString can be used to format numbers according to different languages (the term "locale" is a misnomer) and currencies. However, while ECMA-402 (on which the options to toLocaleString are based) uses the established ISO 3217 codes for currencies, it allows implementations to vary their representation so users may get standard codes for some (e.g. FJD for Fiji dollar), non–standard letters and symbols for a few (e.g. NZ$ for New Zealand dollar), and just symbols for others (e.g. $ for US dollar) (see EMCA-402 §6.3).
So users are still left wondering which currency a symbol represents for currencies used in multiple countries, e.g.
Is $ for US, Australian, New Zealand or Fiji dollar (and many others)?
Is £ for British, Lebanese or Egyptian pound (and many others)?
If you have an application that you want to accurately reflect currencies in a format familiar to the user:
Prefix the number with the correct ISO 3217 code
Specify the language as undefined
Format the number using the required number of decimal places.
E.g.
var num = 3000000;
var currencies = ['USD','NZD','FJD','EUR','GBP','EGP','LBP','MRO','JPY']
console.log('toString variants (the first 3 are all dollars)\n');
currencies.forEach(function(c){
console.log(c + ': ' + num.toLocaleString(undefined, {style: 'currency', currency: c}));
});
console.log('Consistent with ISO 4217\n');
currencies.forEach(function(c) {
console.log(c + ': ' + c + num.toLocaleString(undefined,
{minimumFractionDigits: 2, maximumFractionDigits: 2}));
});
Using the ISO currency code means all currencies are treated equally and there's no confusion over symbology.
There are only two countries that don't use decimal currencies: Madagascar (1 ariary = 5 iraimbilanja) and Mauritania (1 ouguiya = 5 khoums). toLocaleString doesn't do anything special with those currencies, so you'll need special handling if you wish to accommodate their minor units. You may want to support older (or ancient) non–decimal currencies like the old British pound or Greek drachma, but you'll need special handling for those too.

Categories