I have a text box that will have a currency string in it that I then need to convert that string to a double to perform some operations on it.
"$1,100.00" → 1100.00
This needs to occur all client side. I have no choice but to leave the currency string as a currency string as input but need to cast/convert it to a double to allow some mathematical operations.
Remove all non dot / digits:
var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9.-]+/g,""));
accounting.js is the way to go. I used it at a project and had very good experience using it.
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
accounting.unformat("€ 1.000.000,00", ","); // 1000000
You can find it at GitHub
Use a regex to remove the formating (dollar and comma), and use parseFloat to convert the string to a floating point number.`
var currency = "$1,100.00";
currency.replace(/[$,]+/g,"");
var result = parseFloat(currency) + .05;
I know this is an old question but wanted to give an additional option.
The jQuery Globalize gives the ability to parse a culture specific format to a float.
https://github.com/jquery/globalize
Given a string "$13,042.00", and Globalize set to en-US:
Globalize.culture("en-US");
You can parse the float value out like so:
var result = Globalize.parseFloat(Globalize.format("$13,042.00", "c"));
This will give you:
13042.00
And allows you to work with other cultures.
I know this is an old question, but CMS's answer seems to have one tiny little flaw: it only works if currency format uses "." as decimal separator.
For example, if you need to work with russian rubles, the string will look like this:
"1 000,00 rub."
My solution is far less elegant than CMS's, but it should do the trick.
var currency = "1 000,00 rub."; //it works for US-style currency strings as well
var cur_re = /\D*(\d+|\d.*?\d)(?:\D+(\d{2}))?\D*$/;
var parts = cur_re.exec(currency);
var number = parseFloat(parts[1].replace(/\D/,'')+'.'+(parts[2]?parts[2]:'00'));
console.log(number.toFixed(2));
Assumptions:
currency value uses decimal notation
there are no digits in the string that are not a part of the currency value
currency value contains either 0 or 2 digits in its fractional part *
The regexp can even handle something like "1,999 dollars and 99 cents", though it isn't an intended feature and it should not be relied upon.
Hope this will help someone.
This example run ok
var currency = "$1,123,456.00";
var number = Number(currency.replace(/[^0-9\.]+/g,""));
console.log(number);
For anyone looking for a solution in 2021 you can use Currency.js.
After much research this was the most reliable method I found for production, I didn't have any issues so far. In addition it's very active on Github.
currency(123); // 123.00
currency(1.23); // 1.23
currency("1.23") // 1.23
currency("$12.30") // 12.30
var value = currency("123.45");
currency(value); // 123.45
typescript
import currency from "currency.js";
currency("$12.30").value; // 12.30
This is my function. Works with all currencies..
function toFloat(num) {
dotPos = num.indexOf('.');
commaPos = num.indexOf(',');
if (dotPos < 0)
dotPos = 0;
if (commaPos < 0)
commaPos = 0;
if ((dotPos > commaPos) && dotPos)
sep = dotPos;
else {
if ((commaPos > dotPos) && commaPos)
sep = commaPos;
else
sep = false;
}
if (sep == false)
return parseFloat(num.replace(/[^\d]/g, ""));
return parseFloat(
num.substr(0, sep).replace(/[^\d]/g, "") + '.' +
num.substr(sep+1, num.length).replace(/[^0-9]/, "")
);
}
Usage : toFloat("$1,100.00") or toFloat("1,100.00$")
// "10.000.500,61 TL" price_to_number => 10000500.61
// "10000500.62" number_to_price => 10.000.500,62
JS FIDDLE: https://jsfiddle.net/Limitlessisa/oxhgd32c/
var price="10.000.500,61 TL";
document.getElementById("demo1").innerHTML = price_to_number(price);
var numberPrice="10000500.62";
document.getElementById("demo2").innerHTML = number_to_price(numberPrice);
function price_to_number(v){
if(!v){return 0;}
v=v.split('.').join('');
v=v.split(',').join('.');
return Number(v.replace(/[^0-9.]/g, ""));
}
function number_to_price(v){
if(v==0){return '0,00';}
v=parseFloat(v);
v=v.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
v=v.split('.').join('*').split(',').join('.').split('*').join(',');
return v;
}
You can try this
var str = "$1,112.12";
str = str.replace(",", "");
str = str.replace("$", "");
console.log(parseFloat(str));
let thousands_seps = '.';
let decimal_sep = ',';
let sanitizeValue = "R$ 2.530,55".replace(thousands_seps,'')
.replace(decimal_sep,'.')
.replace(/[^0-9.-]+/, '');
// Converting to float
// Result 2530.55
let stringToFloat = parseFloat(sanitizeValue);
// Formatting for currency: "R$ 2.530,55"
// BRL in this case
let floatTocurrency = Number(stringToFloat).toLocaleString('pt-BR', {style: 'currency', currency: 'BRL'});
// Output
console.log(stringToFloat, floatTocurrency);
I know you've found a solution to your question, I just wanted to recommend that maybe you look at the following more extensive jQuery plugin for International Number Formats:
International Number Formatter
How about simply
Number(currency.replace(/[^0-9-]+/g,""))/100;
Works with all currencies and locales. replaces all non-numeric chars (you can have €50.000,00 or $50,000.00) input must have 2 decimal places
jQuery.preferCulture("en-IN");
var price = jQuery.format(39.00, "c");
output is: Rs. 39.00
use jquery.glob.js,
jQuery.glob.all.js
Here's a simple function -
function getNumberFromCurrency(currency) {
return Number(currency.replace(/[$,]/g,''))
}
console.log(getNumberFromCurrency('$1,000,000.99')) // 1000000.99
For currencies that use the ',' separator mentioned by Quethzel Diaz
Currency is in Brazilian.
var currency_br = "R$ 1.343,45";
currency_br = currency_br.replace('.', "").replace(',', '.');
var number_formated = Number(currency_br.replace(/[^0-9.-]+/g,""));
var parseCurrency = function (e) {
if (typeof (e) === 'number') return e;
if (typeof (e) === 'string') {
var str = e.trim();
var value = Number(e.replace(/[^0-9.-]+/g, ""));
return str.startsWith('(') && str.endsWith(')') ? -value: value;
}
return e;
}
This worked for me and covers most edge cases :)
function toFloat(num) {
const cleanStr = String(num).replace(/[^0-9.,]/g, '');
let dotPos = cleanStr.indexOf('.');
let commaPos = cleanStr.indexOf(',');
if (dotPos < 0) dotPos = 0;
if (commaPos < 0) commaPos = 0;
const dotSplit = cleanStr.split('.');
const commaSplit = cleanStr.split(',');
const isDecimalDot = dotPos
&& (
(commaPos && dotPos > commaPos)
|| (!commaPos && dotSplit[dotSplit.length - 1].length === 2)
);
const isDecimalComma = commaPos
&& (
(dotPos && dotPos < commaPos)
|| (!dotPos && commaSplit[commaSplit.length - 1].length === 2)
);
let integerPart = cleanStr;
let decimalPart = '0';
if (isDecimalComma) {
integerPart = commaSplit[0];
decimalPart = commaSplit[1];
}
if (isDecimalDot) {
integerPart = dotSplit[0];
decimalPart = dotSplit[1];
}
return parseFloat(
`${integerPart.replace(/[^0-9]/g, '')}.${decimalPart.replace(/[^0-9]/g, '')}`,
);
}
toFloat('USD 1,500.00'); // 1500
toFloat('USD 1,500'); // 1500
toFloat('USD 500.00'); // 500
toFloat('USD 500'); // 500
toFloat('EUR 1.500,00'); // 1500
toFloat('EUR 1.500'); // 1500
toFloat('EUR 500,00'); // 500
toFloat('EUR 500'); // 500
Such a headache and so less consideration to other cultures for nothing...
here it is folks:
let floatPrice = parseFloat(price.replace(/(,|\.)([0-9]{3})/g,'$2').replace(/(,|\.)/,'.'));
as simple as that.
$ 150.00
Fr. 150.00
€ 689.00
I have tested for above three currency symbols .You can do it for others also.
var price = Fr. 150.00;
var priceFloat = price.replace(/[^\d\.]/g, '');
Above regular expression will remove everything that is not a digit or a period.So You can get the string without currency symbol but in case of " Fr. 150.00 " if you console for output then you will get price as
console.log('priceFloat : '+priceFloat);
output will be like priceFloat : .150.00
which is wrong so you check the index of "." then split that and get the proper result.
if (priceFloat.indexOf('.') == 0) {
priceFloat = parseFloat(priceFloat.split('.')[1]);
}else{
priceFloat = parseFloat(priceFloat);
}
function NumberConvertToDecimal (number) {
if (number == 0) {
return '0.00';
}
number = parseFloat(number);
number = number.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1");
number = number.split('.').join('*').split('*').join('.');
return number;
}
This function should work whichever the locale and currency settings :
function getNumPrice(price, decimalpoint) {
var p = price.split(decimalpoint);
for (var i=0;i<p.length;i++) p[i] = p[i].replace(/\D/g,'');
return p.join('.');
}
This assumes you know the decimal point character (in my case the locale is set from PHP, so I get it with <?php echo cms_function_to_get_decimal_point(); ?>).
You should be able to handle this using vanilla JS. The Internationalization API is part of JS core: ECMAScript Internationalization API
https://www.w3.org/International/wiki/JavaScriptInternationalization
This answer worked for me: How to format numbers as currency strings
I'm building a keypad to enter monetary amounts via touch device.
http://codepen.io/bsley/pen/hrEmK
Once the user has entered 2 digits, I append a decimal. However, once they enter 4 digits, I need to carry the decimal over so it's always 2 digits from the end of the string of numbers.
This way the string always appears as dollars and cents.
I've not been able to find a way to .append X digits from the end of the string in #numBox. Also, even if I was able to, there would need to be someway to search the string for the old decimal and remove it before adding another one digit over to the right.
Any help? Happy to explain further if this isn't concise. Be patient, I'm a total SO noob.
Fixed the issue
if (digits %2 == 0)
{
var mystring = $( "#numBox" ).html();
mystring = mystring.replace('.','');
$( "#numBox" ).html(mystring);
$( "#numBox" ).append(".");
console.log("worked!");
}
Check the updated code on http://codepen.io/bsley/pen/hrEmK
Try this
$(document).ready(function(){
var digits = 0;
var numBox = document.getElementById('numBox');
$('.key').click(function(){
if(this.innerHTML == '0'){
if (numBox.innerHTML.length > 0)
numBox.innerHTML = numBox.innerHTML + this.innerHTML;
digits += 1;
//console.log("digits");
}
else
// add digits
numBox.innerHTML = numBox.innerHTML + this.innerHTML;
digits += 1;
//console.log(digits);
event.stopPropagation();
});
$('.btn').click(function(){
if(this.innerHTML == 'DEL'){
var numBox = document.getElementById('numBox');
if(numBox.innerHTML.length > 0){
// delete a digit
numBox.innerHTML = numBox.innerHTML.substring(0, numBox.innerHTML.length - 1);
digits -= 1;
//console.log(digits);
}
}
else{
// clear numbox
document.getElementById('numBox').innerHTML = '';
digits = 0;
//console.log(digits);
}
event.stopPropagation();
_checkForDecimals();
});
//decimal entry
$('.key').click(function(){
_checkForDecimals();
});
function _checkForDecimals()
{
if (digits > 2) {
var mystring = $( "#numBox" ).html();
mystring = mystring.replace('.','');
var firstPartOfString = mystring.slice(0, mystring.length - 2);
var secondPartOfString = mystring.slice( mystring.length - 2,mystring.length);
//alert(firstPartOfString+'.'+secondPartOfString)
mystring = firstPartOfString+'.'+secondPartOfString;
$( "#numBox" ).html(mystring);
//$( "#numBox" ).append(".");
console.log("worked!");
}
}
});
try something like this
var str = "12.345";
str= str.replace("\.","");
if(str.length > 2){
str = str.substr(0, str.length - 2) + '.' + str.substr(str.length - 2);
}
alert(str);
I checked your fix.But it seems to have an issue.If you press all the keys from 1 to 9, the number becomes 12345678.9. But as per your requirement it should have been 1234567.89 [if I understood correctly].
Please try the below solution and see if it fits your requirement. Please note, at the end of the code block I've added two functions "GetNumberAfterAppendingDecimal" and "GetCleanString" and I've used then on $(.key).click();
$('.key').click(function(){
var inputNumber=GetCleanString($("#numBox").html());
$("#numBox").html(GetNumberAfterAppendingDecimal(inputNumber));
});
function GetNumberAfterAppendingDecimal(str) {
if (str.length < 3)
return str;
var positionFromEnd = 2;
var reversedStr = str.split('').reverse().join('');
if (str.length == 3)
positionFromEnd -= 1;
reversedStr = [reversedStr.slice(0, positionFromEnd), ".", reversedStr.slice(positionFromEnd)].join('');
return reversedStr.split('').reverse().join('');
}
function GetCleanString(str) {
str = str.replace(/[\r]+/, '');
str = str.replace(/[\n]+/, '');
str = str.replace(/[\t]+/, '');
str = str.replace('.', '');
str = $.trim(str);
return str;
}
Very simple, just repleat the code inside $(.key).onclick() for $(div.btn).onclick()..see below :
$('div.btn').click(function(){
var inputNumber=GetCleanString($("#numBox").html());
$("#numBox").html(GetNumberAfterAppendingDecimal(inputNumber));
});
So I'm rewriting dates in javacript and as familiar js spits dates like 2013-1-1 that isn't very useful always. Instead I'm looking for a routine that will form this date to the correct iso-version 2013-01-01
Today I make this by using string
var b = new Date('2013-1-1');
var result = b.getFullYear() + "-" +
(b.getMonth().toString().length == 1 ? "0" + parseInt(b.getMonth() + 1) : parseInt(b.getMonth() + 1)) + "-" +
(b.getDate().toString().length == 1 ? "0" + b.getDate() : b.getDate());
This works but it is ugly. Is there a better way to perform this using RegEx?
Please spare me of any anti-regex comments
A non-regex solution would be a generic padding function. First get your date in the non-padded version then you can split on the separator and pad it as necessary. Something like this:
var date = '2013-1-1';
var pad = function(n) {
return function(str) {
while (str.length < n) {
str = '0'+ str;
}
return str;
}
};
date = date.split(/-/g).map(pad(2)).join('-'); //=> 2013-01-01
may be this could help:
var str="2013-1-1";
var m = str.match(/^(\d{4})-(\d{1})-(\d{1})$/);
console.log([m[1], "0".concat([2]-1), "0".concat(m[3])].join('-'));
based on elclanrs suggestion I wrote an extension method
// Add 0 to single numbers
Number.prototype.padDate = function () {
// Add +1 if input is 0 (js months starts at 0)
var number = this == 0 ? 1 : this;
return number.toString().length == 1 ? "0" + number : number;
};
This allows me to build dates like this
var b = new Date('2013-1-1');
var result = b.getFullYear() + "-" + b.getMonth().padDate() + "-" + b.getDate().padDate();
Much cleaner, thanks
This question already has answers here:
How to format numbers as currency strings
(67 answers)
Closed 9 years ago.
I want to display the dollar timer which goes from 1 to 2500. When the timer increases to 1000, I want to display it as $1,000 instead of $1000. I want commas in thousands place.Could someone help me with this JavaScript.
Thanks.
You could easily do this with a regular expression.
var friendlyNum = (num + "").replace(/^(\d)(\d{3})$/, "$1,$2");
Note that this will only handle 1000 places.
How it works is an exercise to the reader. For learning how they work, stat here.
Even though it's been written a thousand times, I felt like writing some JS.
var addCommas = function(number) {
number = '' + number;
var negative = false;
if (number.match(/^\-/)) {
negative = true;
}
number = number.replace(/[^0-9\.]/g, '');
number = number.split('.');
var before = number.shift()
, after = number.join('');
for (var i = (before.length - 3); i > 0; i -= 3) {
before = before.substr(0, i) + ',' + before.substr(i)
}
return (negative ? '-' : '') + before + (after ? '.' + after : '');
}
// 1,000.00
addCommas(1000.00);
// -1,234,567,890
addCommas('-1234567890');
Below is the approach to convert number format (comma separated)
HTML :-
<input type="text" onkeyup="convertNumberFormat(this.value)" />
JavaScript:-
function convertNumberFormat(inputValue)
{
inputValue = inputValue.toString();
inputValue = inputValue.replace( /\,/g, "");
var x = inputValue.split( '.' );
var intValue = x[0];
var floatValue = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while ( rgx.test(intValue) ) {
intValue = intValue.replace( rgx, '$1' + ',' + '$2' );
}
alert(intValue + floatValue);
}
In HTML template I am calling this function at "onkeyup" event.
you just need to call "convertNumberFormat" function whenever you want to validate your input value and pass current inserted value...
Example:-
convertNumberFormat('$2500');
Output:-
'$2,500' // in alert.
hope this can help you...
I have these numbers
10999 and 8094 and 456
And all i want to do is add a comma in the right place if it needs it so it looks like this
10,999 and 8,094 and 456
These are all within a p tag like this <p class="points">10999</p> etc.
Can it be done?
I've attempted it here with the help of other posts http://jsfiddle.net/pdWTU/1/ but can't seem to get it to work
Thanks
Jamie
UPDATE
Messed around a bit and managed to figure it out here http://jsfiddle.net/W5jwY/1/
Going to look at the new Globalization plugin for a better way of doing it
Thanks
Jamie
Works on all browsers, this is all you need.
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
Wrote this to be compact, and to the point, thanks to regex. This is straight JS, but you can use it in your jQuery like so:
$('#elementID').html(commaSeparateNumber(1234567890));
or
$('#inputID').val(commaSeparateNumber(1234567890));
However, if you require something cleaner, with flexibility. The below code will fix decimals correctly, remove leading zeros, and can be used limitlessly. Thanks to #baacke in the comments.
function commaSeparateNumber(val){
val = val.toString().replace(/,/g, ''); //remove existing commas first
var valRZ = val.replace(/^0+/, ''); //remove leading zeros, optional
var valSplit = valRZ.split('.'); //then separate decimals
while (/(\d+)(\d{3})/.test(valSplit[0].toString())){
valSplit[0] = valSplit[0].toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
if(valSplit.length == 2){ //if there were decimals
val = valSplit[0] + "." + valSplit[1]; //add decimals back
}else{
val = valSplit[0]; }
return val;
}
And in your jQuery, use like so:
$('.your-element').each(function(){
$(this).html(commaSeparateNumber($(this).html()));
});
Here's the jsFiddle.
Number(10000).toLocaleString('en'); // "10,000"
Timothy Pirez answer was very correct but if you need to replace the numbers with commas Immediately as user types in textfield, u might want to use the Keyup function.
$('#textfield').live('keyup', function (event) {
var value=$('#textfield').val();
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var newvalue=value.replace(/,/g, '');
var valuewithcomma=Number(newvalue).toLocaleString('en');
$('#textfield').val(valuewithcomma);
});
<form><input type="text" id="textfield" ></form>
Take a look at recently released Globalization plugin to jQuery by Microsoft
Take a look at Numeral.js. It can format numbers, currency, percentages and has support for localization.
function delimitNumbers(str) {
return (str + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, "$1,") : b) + c;
});
}
alert(delimitNumbers(1234567890));
I'm guessing that you're doing some sort of localization, so have a look at this script.
Using toLocaleString
ref at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
function formatComma(value, sep = 0) {
return Number(value).toLocaleString("ja-JP", { style: "currency", currency: "JPY", minimumFractionDigits: sep });
}
console.log(formatComma(123456789, 2)); // ¥123,456,789.00
console.log(formatComma(123456789, 0)); // ¥123,456,789
console.log(formatComma(1234, 0)); // ¥1,234
another approach:
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
var a = addCommas(10000.00);
alert(a);
Another amazing plugin:
http://www.teamdf.com/web/jquery-number-format/178/
Another way to do it:
function addCommas(n){
var s = "",
r;
while (n) {
r = n % 1000;
s = r + s;
n = (n - r)/1000;
s = (n ? "," : "") + s;
}
return s;
}
alert(addCommas(12345678));
Here is my coffeescript version of #baacke's fiddle provided in a comment to #Timothy Perez
class Helpers
#intComma: (number) ->
# remove any existing commas
comma = /,/g
val = number.toString().replace comma, ''
# separate the decimals
valSplit = val.split '.'
integer = valSplit[0].toString()
expression = /(\d+)(\d{3})/
while expression.test(integer)
withComma = "$1,$2"
integer = integer.toString().replace expression, withComma
# recombine with decimals if any
val = integer
if valSplit.length == 2
val = "#{val}.#{valSplit[1]}"
return val