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.
Related
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 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.
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.
I am attempting to develop a conversion website that takes a numeric value:
1,200.12
or
1.200,12
or
1200.12
or
1200,12
and have them all interpreted as 1200.12 by parseFloat.
I would also like decimals to be able to be interpreted.
0.123
or
0,123
as 0.123
through a textarea and then parseFloat the number in order to perform calculations.
These are the results I am getting:
textarea input = 12,000.12
value after parseFloat = 12
Does parseFloat not recognize the formatting of the numbers?
i get the same results with:
textarea input: 12.000,12
value after parseFloat = 12
How do I solve this problem? It would seem I need to strip out the commas since parseFloat doesn't read beyond them and with european notation strip the decimals and change the comma to a decimal for parseFloat to read the input correctly. Any ideas on how to solve this? My guess is I would need to identify the string input as either european or american decimal notation and then perform the required actions to prepare the string for parseFloat. How would I go about achieving that? All contributions are appreciated. Using HTML5 and Javascript. This is my first website so please go easy on me.
Best,
RP
To all contributors...Thank you! So far all the input has been sweet. I don't think we are going to be able to use a single replace statement to correctly strip both european and american notation so I think I should use REGEX somehow to determine the notation and then split into an if else statement to perform separate replace functions on each individual notation.
var input, trim;
input = "1.234,56" //string from textarea on page
if(/REGEX that determines American Notation/.test(input){
trim = input.replace(/\,/,"");//removes commas and leaves decimal point);
}
else(/REGEX that determine European Notation/.test(input)/){ //would qualify input here
rep = input.replace(/\./,"");//removes all decimal points);
trim = rep.replace(/\,/,"."//changes the remaining comma to a decimal);
}
//now either notation should be in the appropriate form to parse
number = parseFloat(trim);
Is this possible using REGEX? Please see my other question.
Regex - creating an input/textarea that correctly interprets numbers
One way would be to strip the comma signs, for example with:
.replace(",", "")
From there you should be able to parseFloat
Updated with fiddle: http://jsfiddle.net/aLv74xpu/2/
Here is a solution that uses a regular expression to eliminate all commas and all periods, except the last one.
var number = "1,234.567.890";
var replaced = number.replace(/,|\.(?=.*\.)/g, "");
var result = parseFloat(replaced);
// result === 1234567.89
Alternatively, you can use this, which treats commas and periods identically, and ignores them all except for the last one.
var number = "12.345,67";
var replaced = number.replace(/[.,](?=.*[.,])/g, "").replace(",", ".");
var result = parseFloat(replaced);
// result === 12345.67
parseFloat parses its argument, a string, and returns a floating point
number. If it encounters a character other than a sign (+ or -),
numeral (0-9), a decimal point, or an exponent, it returns the value
up to that point and ignores that character and all succeeding
characters. Leading and trailing spaces are allowed.
From the good MDN network: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
So it is the expected behaviour of parseFloat
I get the value 17.000, 17 thousands.
var pay = document.getElementbyId("name").InnerHTML;
alert(pay);
it shows "17.000". But if I do like this:
var f = (pay * 24);
alert(f);
it shows 408, not 408.000. It makes 17 * 24 not 17.000 * 24. How to work around this?
The period is the decimal point in the English language. If you want "17.000" to be treated as seventeen-thousand and not seventeen, you have to remove the period:
var pay = +document.getElementById("name").innerHTML.replace(/\./g, '');
The unary plus (+) at the beginning converts the resulting string into a number. This is not strictly necessary in your example but can avoid problems in the long run.
Using parseFloat exposes the same problem as implicit type conversion.
If you want to format the number (i.e. convert it to a string with thousand separators) again, have a look at How to print a number with commas as thousands separators in JavaScript. Just use a period instead of a comma.