Adding a prefix and commas in a Javascript counter - javascript

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.

Related

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 get space between currency code and amount using localeString in JavaScript?

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);

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

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.

Javascript regex for multiple currencies

I need to fetch the currency from a string. My price can have multiple format. Let's take for example CAD vs USD. CAD will be formatted this way :
5.00$ CAD
While USD will be formatted this way
$5.00 USD
The system also support euro, and GBP. Obviously the price could be in the tousands.
Here is my unsuccessful attempt :
result = /^([^\$]+)\$/i.exec(price.text());
Don't overthink it.
/(\d|\.)+/
will pull out the number.
You can also do a replace, per adeneo, to clean it up:
price.replace(/[^0-9.]/g, '')
and then parseFloat if you need to.
Wow - I'm not sure I understand - you only want to extract the number (thousands, wholes and decimal portions) buit not the type of currency??? what about exchange rates?? are there other columns that indicate the currency type? just seems weird...
But if the column only contains a string with the amnount and currency indicators, then [\d.,]+ should get the number (and any trailing or leading commas or periods) - does that work for you?
Money is commonly represented as an [int, currency] tuple. I'd aim towards a format like that.
Your string seems to have a bit of fluff in it. The $ for one.
So how about:
var db_string = "5.00$ CAD"; // or "$5.00 USD" or "€5.00 EUR"
var clean = db_string.replace(/[0-9A-Z ]/g, ""); // removes $ . and euro etc.
var parts = clean.split(" ");
var num = parseInt(parts[0], 10); // amount as int, in cents
var cur = parts[1]; // currency: USD, CAD, EUR etc.

Categories