Related
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 am creating a function that returns whether the passed in number is odd Without the modulo operator. The tricky part is that it should work for NEGATIVE numbers and ZERO.
here's my codes so far:
function testodd(num) {
return (num/2)*2==num;
}
var output = testodd(17);
console.log(output); // --> true
Am I making some mistakes here? Or is there a better way to do this?
you can use Bitwise operator and get same result. does this help.
<script type="text/javascript">
function oddOrEven(x) {
return ( x & 1 ) ? "odd" : "even";
}
console.log(oddOrEven(10));
</script>
For more detail about bitwise operator
Hi you can do it with bitwise AND (&) operator to check if a number is even or odd.
function testodd(num) {
if((num & 1) == 0){
return true
}
return false;
}
var output = testodd(17);
console.log(output); // --> false
var output = testodd(-16);
console.log(output); // --> true
var output = testodd(0);
console.log(output); // --> true
Try a bit-wise operation
function testodd(num) {
return num & 1; // num AND 0x1 checks for the least significant bit, indicating true or falsey
}
Remove the decimal part after division using Math.floor.
Math.floor(num / 2) * 2 === num;
For even numbers, there is no loss in decimal value. For odd numbers, decimal point value will be lost and comparison will falsy.
Here is a horribly inefficient method using recursion:
function checkOdd(num)
{
num = Math.abs(num);
if(num==0)
return false;
else if(num==1)
return true;
else
return checkOdd(num-2);
}
Of course you should never use it.
Since there's already an answer I will show you an alternative away of doing it with regex
function checkOdd(num){
console.log(/^\d*[13579]$/.test(num));
}
checkOdd(105);
Would only work with reasonably sized integers
Try
function testodd(num){
if num < 0{
var number = -num
}
int i = 1;
int product = 0;
while (product <= num)
{
product = divisor * i;
i++;
}
// return remainder
return num - (product - divisor);
}
Use this function to check if a number is odd or even, without using the modulo operator %. This should work for negative numbers and zero.
function checkOdd(num) {
// your code here
if(num<0){ //Check if number is negative
num=-num; //Convert it into positive number
}
let b=Math.floor(num/2) //Taking value for loop iteration
for(var i=1;i<=b;i++){
num=num-2; //Will check the number is odd if it subtraction end to 1 by decrementing -2 to the number
if(num==1){
return true; //return true if number is odd
}
}
return false; //return false if number is even
}
You can use isInteger method
function isEven(n){
return Number.isInteger(n / 2);
}
function odd(num) {
if (num === 0) {
return false;
}
num = Math.abs(num);
while (num >= 2) {
num = num - 2;
}
if (num === 1) {
return true;
} else {
return false;
}
}
Even number
lets take an even number say 6;
6 divided by 2 is 3;
Math.round(3) is 3;
Math.floor(3) is 3;
3===3 eveluates to true so 6 is an even number;
Odd number
lets take an odd number say 9;
9 divided by 2 is 4.5;
Math.round(4.5) is 5;
Math.floor(4.5) is 4;
5===4 evaluates to false so 9 is an odd number;
function evenChecked(num) {
if (Math.round(num / 2) === Math.floor(num / 2)) {
return `${num} is even`;
} else {
return `${num} is odd`;
}
}
console.log(evenChecked(23));
console.log(evenChecked(90));
console.log(evenChecked(56));
console.log(evenChecked(49));
I want to check if a number is equal to 1 or every 5th number after that.
Eg. 1,6,11,16,21,... Then I want to set a value.
Something like
if (checkForOneOrFifth(rowNumber)){
$("#x"+rowNumber+"_Location").val('myText');
$("#x"+rowNumber+1+"_Location").val('myText');
$("#x"+rowNumber+2+"_Location").val('myText');
$("#x"+rowNumber+3+"_Location").val('myText');
$("#x"+rowNumber+4+"_Location").val('myText');
}
var checkForOneOrFifth = function(number) {
if(something here){
return true;
}else{
return false;
}
};
Thanks for any help
Scott
You can use the mod operator to check that for you:
var checkforoneorffith = function(number){
return (number - 1) % 5 == 0;
}
I'm trying to make a decimal to hexadecimal converter without using Number.prototype.toString (this is an assignment which does not allow that function). I am attempting to use recursion to try to work it. Everything works until the else inside the main else if that makes any sense. It gives me that error when I run it for any number above 255 (i.e. any number which has more than 2 digits in hexadecimal). Does anyone know why this is the case?
var number = parseInt(prompt("Give me a number and I will turn it into hexadecimal!"));
var digit = 1;
var hexConverter = function () {
if (digit === 1) {
if (Math.floor(number / 16) === 0) {
console.log(hexDigits[number]);
} else {
digit = 16;
console.log(hexConverter(), hexDigits[number % 16]);
}
} else {
if (Math.floor(number / (digit * 16)) === 0) {
return (hexDigits[Math.floor(number / digit)]);
} else {
return (hexConverter(), hexDigits[number % (digit * 16)]);
}
digit = digit * 16;
}
};
hexConverter();
You are changing digit after making the recursive call, so it will be stuck at 16 and never get to the point where you increase it.
Move the digit = digit*16; to before the recursive call, just as you have digit = 16 in the first part.
function toHex(x) {
var res='',h;
while (x) {
res=(((h=x&15)<10)? h : String.fromCharCode(55+h)) + res;
x>>=4;
}
return res;
}
Would work quite fine.
Question to you : why only 'quite' ? :-)
I am looking for an easy way in JavaScript to check if a number has a decimal place in it (in order to determine if it is an integer). For instance,
23 -> OK
5 -> OK
3.5 -> not OK
34.345 -> not OK
if(number is integer) {...}
Using modulus will work:
num % 1 != 0
// 23 % 1 = 0
// 23.5 % 1 = 0.5
Note that this is based on the numerical value of the number, regardless of format. It treats numerical strings containing whole numbers with a fixed decimal point the same as integers:
'10.0' % 1; // returns 0
10 % 1; // returns 0
'10.5' % 1; // returns 0.5
10.5 % 1; // returns 0.5
Number.isInteger(23); // true
Number.isInteger(1.5); // false
Number.isInteger("x"); // false:
Number.isInteger() is part of the ES6 standard and not supported in IE11.
It returns false for NaN, Infinity and non-numeric arguments while x % 1 != 0 returns true.
Or you could just use this to find out if it is NOT a decimal:
string.indexOf(".") == -1;
Simple, but effective!
Math.floor(number) === number;
The most common solution is to strip the integer portion of the number and compare it to zero like so:
function Test()
{
var startVal = 123.456
alert( (startVal - Math.floor(startVal)) != 0 )
}
Number.isSafeInteger(value);
In JavaScript, isSafeInteger() is a Number method that is used to return a Boolean value indicating whether a value is a safe integer. This means that it is an integer value that can be exactly represented as an IEEE-754 double precision number without rounding.
//How about byte-ing it?
Number.prototype.isInt= function(){
return this== this>> 0;
}
I always feel kind of bad for bit operators in javascript-
they hardly get any exercise.
Number.isInteger() is probably the most concise. It returns true if it is an integer, and false if it isn't.
number = 20.5
if (number == Math.floor(number)) {
alert("Integer")
} else {
alert("Decimal")
}
Pretty cool and works for things like XX.0 too!
It works because Math.floor() chops off any decimal if it has one so if the floor is different from the original number we know it is a decimal! And no string conversions :)
var re=/^-?[0-9]+$/;
var num=10;
re.test(num);
convert number string to array, split by decimal point. Then, if the array has only one value, that means no decimal in string.
if(!number.split(".")[1]){
//do stuff
}
This way you can also know what the integer and decimal actually are. a more advanced example would be.
number_to_array = string.split(".");
inte = number_to_array[0];
dece = number_to_array[1];
if(!dece){
//do stuff
}
function isDecimal(n){
if(n == "")
return false;
var strCheck = "0123456789";
var i;
for(i in n){
if(strCheck.indexOf(n[i]) == -1)
return false;
}
return true;
}
parseInt(num) === num
when passed a number, parseInt() just returns the number as int:
parseInt(3.3) === 3.3 // false because 3 !== 3.3
parseInt(3) === 3 // true
Use following if value is string (e.g. from <input):
Math.floor(value).toString() !== value
I add .toString() to floor to make it work also for cases when value == "1." (ends with decimal separator or another string). Also Math.floor always returns some value so .toString() never fails.
Here's an excerpt from my guard library (inspired by Effective JavaScript by David Herman):
var guard = {
guard: function(x) {
if (!this.test(x)) {
throw new TypeError("expected " + this);
}
}
// ...
};
// ...
var number = Object.create(guard);
number.test = function(x) {
return typeof x === "number" || x instanceof Number;
};
number.toString = function() {
return "number";
};
var uint32 = Object.create(guard);
uint32.test = function(x) {
return typeof x === "number" && x === (x >>> 0);
};
uint32.toString = function() {
return "uint32";
};
var decimal = Object.create(guard);
decimal.test = function(x) {
return number.test(x) && !uint32.test(x);
};
decimal.toString = function() {
return "decimal";
};
uint32.guard(1234); // fine
uint32.guard(123.4); // TypeError: expected uint32
decimal.guard(1234); // TypeError: expected decimal
decimal.guard(123.4); // fine
You can multiply it by 10 and then do a "modulo" operation/divison with 10, and check if result of that two operations is zero. Result of that two operations will give you first digit after the decimal point.
If result is equal to zero then the number is a whole number.
if ( (int)(number * 10.0) % 10 == 0 ){
// your code
}
function isDecimal(num) {
return (num !== parseInt(num, 10));
}
You can use the bitwise operations that do not change the value (^ 0 or ~~) to discard the decimal part, which can be used for rounding. After rounding the number, it is compared to the original value:
function isDecimal(num) {
return (num ^ 0) !== num;
}
console.log( isDecimal(1) ); // false
console.log( isDecimal(1.5) ); // true
console.log( isDecimal(-0.5) ); // true
function isWholeNumber(num) {
return num === Math.round(num);
}
When using counters with decimal steps, checking if number is round will actually fail, as shown below. So it might be safest (although slow) to format the number with 9 (could be more) decimal places, and if it ends with 9 zeros, then it's a whole number.
const isRound = number => number.toFixed(9).endsWith('000000000');
for (let counter = 0; counter < 2; counter += 0.1) {
console.log({ counter, modulo: counter % 1, formatted: counter.toFixed(9), isRound: isRound(counter) });
}
Perhaps this works for you?
It uses regex to check if there is a comma in the number, and if there is not, then it will add the comma and stripe.
var myNumber = '50';
function addCommaStripe(text){
if(/,/.test(text) == false){
return text += ',-';
} else {
return text;
}
}
myNumber = addCommaStripe(myNumber);
You can use this:
bool IsInteger() {
if (num.indexOf(".") != -1) // a decimal
{
return Math.ceil(num) == Math.floor(num); // passes for 1.0 as integer if thats the intent.
}
return Number.isSafeInteger(num);
}
to check if the number is integer or decimal.
Using Number.isInteger(num) can help check what would count as whole number and what would not.
For example:
let num1 = 6.0000000000000001; // 16 decimal places
let num2 = 6.000000000000001; // 15 decimal places
Number.isInteger(num1); // true, because of loss of precision
// while:
Number.isInteger(num2); // false
So, in my opinion it's safe to use Number.isInteger() over other suggested ways if what you need is to know what is an integer mathematically.
Function for check number is Decimal or whole number
function IsDecimalExist(p_decimalNumber) {
var l_boolIsExist = true;
if (p_decimalNumber % 1 == 0)
l_boolIsExist = false;
return l_boolIsExist;
}