Remove commas from the string using JavaScript - javascript

I want to remove commas from the string and calculate those amount using JavaScript.
For example, I have those two values:
100,000.00
500,000.00
Now I want to remove commas from those string and want the total of those amount.

To remove the commas, you'll need to use replace on the string. To convert to a float so you can do the maths, you'll need parseFloat:
var total = parseFloat('100,000.00'.replace(/,/g, '')) +
parseFloat('500,000.00'.replace(/,/g, ''));

Related answer, but if you want to run clean up a user inputting values into a form, here's what you can do:
const numFormatter = new Intl.NumberFormat('en-US', {
style: "decimal",
maximumFractionDigits: 2
})
// Good Inputs
parseFloat(numFormatter.format('1234').replace(/,/g,"")) // 1234
parseFloat(numFormatter.format('123').replace(/,/g,"")) // 123
// 3rd decimal place rounds to nearest
parseFloat(numFormatter.format('1234.233').replace(/,/g,"")); // 1234.23
parseFloat(numFormatter.format('1234.239').replace(/,/g,"")); // 1234.24
// Bad Inputs
parseFloat(numFormatter.format('1234.233a').replace(/,/g,"")); // NaN
parseFloat(numFormatter.format('$1234.23').replace(/,/g,"")); // NaN
// Edge Cases
parseFloat(numFormatter.format(true).replace(/,/g,"")) // 1
parseFloat(numFormatter.format(false).replace(/,/g,"")) // 0
parseFloat(numFormatter.format(NaN).replace(/,/g,"")) // NaN
Use the international date local via format. This cleans up any bad inputs, if there is one it returns a string of NaN you can check for. There's no way currently of removing commas as part of the locale (as of 10/12/19), so you can use a regex command to remove commas using replace.
ParseFloat converts the this type definition from string to number
If you use React, this is what your calculate function could look like:
updateCalculationInput = (e) => {
let value;
value = numFormatter.format(e.target.value); // 123,456.78 - 3rd decimal rounds to nearest number as expected
if(value === 'NaN') return; // locale returns string of NaN if fail
value = value.replace(/,/g, ""); // remove commas
value = parseFloat(value); // now parse to float should always be clean input
// Do the actual math and setState calls here
}

To remove commas, you will need to use string replace method.
var numberArray = ["1000,00", "23", "11"];
//If String
var arrayValue = parseFloat(numberArray.toString().replace(/,/g, ""));
console.log(arrayValue, "Array into toString")
// If Array
var number = "23,949,333";
var stringValue = parseFloat(number.replace(/,/g, ""));
console.log(stringValue, "using String");

Related

Perform calculation after adding Commas to the number

I have the following function which adds commas to the text field. Example: 5000000 is returned as 5,000,000.
function addComma(values) {
values.value = values.value.replace(",", "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
if (document.getElementById("values"))
payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">
However, I am not able to use it any further with other variables. If i remove parseInt, it returns NAN and adding parseInt returns 5.
payment = 10;
values = 5,000,000
The following returns PV = payment * NAN5,000,000 while debugging.
PV = payment*values;
What am i doing wrong here? Any help is appreciated. Thank you!
you can get rid of commas by using the below command:
values = values.replace(/\,/g,'')
this essencially removed all the commas from your string
now, convert the string validly representing a number to a number indeed using:
values = Number(values)
Hope it helps !!!
You are trying to use parseInt on a string that has commas added.
parseInt will stop parsing after the first non-numeric character:
If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed.
console.log(parseInt('123456')); // 123456
console.log(parseInt('123,456')); // 123
Given this, you should remove the commas before parsing:
function addComma(values) {
values.value = values.value.replace(",", "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
// Moved the rest of the conde into the function so you can
// see the output as you type.
// Get your element by Id into a const so you don't need to query twice.
const element = document.getElementById("values");
if (element) {
// Remove commas from the number to be parsed
const value = element.value.replace(",", "");
// It is best practice to include the radix when calling parseInt
const payment = parseInt(value, 10);
console.log(payment);
}
}
<label>Rent</label> <input id="values" type="text" onkeyup="addComma(this);">
Doing the following worked for me.
payment = document.getElementById("values").value;
var Return = payment.replace(/\,/g,'');
Instead of parseInt i just declared another variable and removes commas to perform any further calculations.

Tokenize a JavaScript String depending on the characters

In JavaScript, let's say I have a String like "23+var-5/422*b".
I want to split this String so that I get [23,+,var,-,5,/,422,*,b].
I want to tokenize it so that I split the string into 3 types of tokens:
Numerical literals, [0-9].
String literals, [A-z].
Operator characters, [-+*/].
So basically, go through the string, and for each "cluster of characters" that share the same class (each with 1 or more characters), convert that into a token.
I could probably use a for loop, comparing each character with each class, and manually create a token every time the current "character class" changes... it would be very tedious and use many variables and loops.
Does anyone know a more elegant (less verbose) way to get there?
A global regexp match will do this for you:
var str = "23+var-5/422*b";
var arr = str.match(/[0-9]+|[a-zA-Z]+|[-+*/]/g); // notice the creation of one token
// per operator (even if consecutive)
However, it simply ignores invalid characters instead of erroring out.
Here's a way to do it using Regex. Obviously the code can be simplified more if you use Underscore.js or CoffeeScript. So here's a longer version using vanilla JS:
var s = "23+var-5/422*b"; // your string
var re1 = /[0-9]/; // Regex for numerals
var re2 = /[a-zA-Z]/; // Regex for roman chars
var re3 = /[-+*\/]/; // Regex you wanted for operators
// Helper function, return true if n none-negative
function nonNegative(n) {
return n >= 0;
}
// helper function: add any none-negative n to array arr
function addNonNegative(n, arr) {
if (nonNegative(n)) {arr.push(n)};
}
// The main function to split string s
function split(s) {
var result = []; // The result array, initialized
// Do while string s is none empty.
while(s.length > 0) {
// The order of indices of regex found
var order = [];
// search for index or which the regex occurs, then if that index is none-negative, add it to the 'order' array
addNonNegative(s.search(re1), order);
addNonNegative(s.search(re2), order);
addNonNegative(s.search(re3), order);
// sort the order array
order = order.sort();
// variables to slice the string s.
// start is always 0. Marks the starting index of the first matched regex
var start = order.shift();
// Marks the starting index of the second matched regex
var end = order.shift(); // end is the second result in order
result.push(s.slice(start, end)); // slice the string s from start to end
// update s so that exclude what was sliced before
s = s.slice(end);
// boundary condition: finally when end is null once all regex have been pulled, set s = ""
if (end == null) {s = ""};
}
return result;
}

Efficiently getting string?

I want to take two values from string
"105.106"
The values 105 and 106 can be different the point(.) will decide their splitting after split i want these values in variable. i have look it into indexOf and split method but not getting logic.
It's quite simple:
var str = "105.106";
var values = str.split('.'); // (or "." or /\./)
console.log(values[0]); // Output: 105
console.log(values[1]); // Output: 106
Live demo.
You can learn more about how split works here. In short, split is a method on the String's prototype that you pass it the character that acts as a delimiter, and it tokenizes the string based on that character. For example, if you had "123,456,789" and you wanted to tokenize the string as if the , was the delimiter, you would get "123", "456", and "789".
Now your string is "105.106", and you want . to act as the delimiter, as such you write something similar to:
tokens = "105.106".split(".");
tokens[0] == "105"; // true
tokens[1] == "106"; // true
As you can see, split has decomposed the string into an array with two components, containing the string splited by the . character.
You can do:
var str = "105.106";
// does the string contain floating point dot ?
if (str.indexOf('.') >= 0) {
var values = str.split('.');
alert(values[0]); // value before dot
alert(values[1]); // value after dot
}
else {
alert(str); // string did not contain a dot/point
}
Above code will give you both values before and after dot/point in case it contains a dot else it will give you string as it was.
The JavaScript String.split(delimiter) method does what you want. Use it like this:
var s = "105.106";
var values = s.split(".");
// values[0] = "105", values[1] = "106".
I've not tested it but guess this may work
var str="xxx.xxxxx";
dot=str.lastIndexOf('.');
num2=str.substring(dot+1);
num1=str.substring(0,dot);

how to check whether a var is string or number using javascript

I have a variable var number="1234", though the number is a numeric value but it is between "" so when I check it using typeof or by NaN I got it as a string .
function test()
{
var number="1234"
if(typeof(number)=="string")
{
alert("string");
}
if(typeof(number)=="number")
{
alert("number");
}
}
I got always alert("string"), can you please tell me how can I check if this is a number?
As far I understand your question you are asking for a test to
detect if a string represents a numeric value.
A quick test should be
function test() {
var number="1234"
return (number==Number(number))?"number":"string"
}
As Number, if called without the new keyword convert the string into a number.
If the variable content is untouched (== will cast back the numeric value to a string)
you are dealing with a number. It is a string otherwise.
function isNumeric(value) {
return (value==Number(value))?"number":"string"
}
/* tests evaluating true */
console.log(isNumeric("1234")); //integer
console.log(isNumeric("1.234")); // float
console.log(isNumeric("12.34e+1")); // scientific notation
console.log(isNumeric(12)); // Integer
console.log(isNumeric(12.7)); // Float
console.log(isNumeric("0x12")); // hex number
/* tests evaluating false */
console.log(isNumeric("1234e"));
console.log(isNumeric("1,234"));
console.log(isNumeric("12.34b+1"));
console.log(isNumeric("x"));
The line
var number = "1234";
creates a new String object with the value "1234". By putting the value in quotes, you are saying that it a string.
If you want to check if a string only contains numeric digits, you can use regular expressions.
if (number.match(/^-?\d+$/)) {
alert("It's a whole number!");
} else if (number.match(/^-?\d+*\.\d+$/)) {
alert("It's a decimal number!");
}
The pattern /^\d+$/ means: at the start (^) of the string, there is an optional minus sign (-?), then a digit (\d), followed by any more digits (+), and then the end of the string ($). The other pattern just looks for a point between the groups of digits.
See parseInt and parseFloat
Convert it to a number then compare it to the original string.
if ( parseFloat(the_string,10) == the_string ) {
// It is a string containing a number (and only a number)
}
because var number="1234" is a string. the double quotes makes it a literal.
if you want a number use it like this
var number = 1234;
Update:
If you are taking the input from a input tag forexample, the dataType will be string, if you want to convert it to a number, you can use the parseInt() function
var number = "1234";
var newNumber = parseInt(number);
alert(typeof newNumber); // will result in string
Another easy way:
var num_value = +value;
if(value !== '' && !isNaN(num_value)) {
// the string contains (is) a number
}

Regex using javascript to return just numbers

If I have a string like "something12" or "something102", how would I use a regex in javascript to return just the number parts?
Regular expressions:
var numberPattern = /\d+/g;
'something102asdfkj1948948'.match( numberPattern )
This would return an Array with two elements inside, '102' and '1948948'. Operate as you wish. If it doesn't match any it will return null.
To concatenate them:
'something102asdfkj1948948'.match( numberPattern ).join('')
Assuming you're not dealing with complex decimals, this should suffice I suppose.
You could also strip all the non-digit characters (\D or [^0-9]):
let word_With_Numbers = 'abc123c def4567hij89'
let word_Without_Numbers = word_With_Numbers.replace(/\D/g, '');
console.log(word_Without_Numbers)
For number with decimal fraction and minus sign, I use this snippet:
const NUMERIC_REGEXP = /[-]{0,1}[\d]*[.]{0,1}[\d]+/g;
const numbers = '2.2px 3.1px 4px -7.6px obj.key'.match(NUMERIC_REGEXP)
console.log(numbers); // ["2.2", "3.1", "4", "-7.6"]
Update: - 7/9/2018
Found a tool which allows you to edit regular expression visually: JavaScript Regular Expression Parser & Visualizer.
Update:
Here's another one with which you can even debugger regexp: Online regex tester and debugger.
Update:
Another one: RegExr.
Update:
Regexper and Regex Pal.
If you want only digits:
var value = '675-805-714';
var numberPattern = /\d+/g;
value = value.match( numberPattern ).join([]);
alert(value);
//Show: 675805714
Now you get the digits joined
I guess you want to get number(s) from the string. In which case, you can use the following:
// Returns an array of numbers located in the string
function get_numbers(input) {
return input.match(/[0-9]+/g);
}
var first_test = get_numbers('something102');
var second_test = get_numbers('something102or12');
var third_test = get_numbers('no numbers here!');
alert(first_test); // [102]
alert(second_test); // [102,12]
alert(third_test); // null
IMO the #3 answer at this time by Chen Dachao is the right way to go if you want to capture any kind of number, but the regular expression can be shortened from:
/[-]{0,1}[\d]*[\.]{0,1}[\d]+/g
to:
/-?\d*\.?\d+/g
For example, this code:
"lin-grad.ient(217deg,rgba(255, 0, 0, -0.8), rgba(-255,0,0,0) 70.71%)".match(/-?\d*\.?\d+/g)
generates this array:
["217","255","0","0","-0.8","-255","0","0","0","70.71"]
I've butchered an MDN linear gradient example so that it fully tests the regexp and doesn't need to scroll here. I think I've included all the possibilities in terms of negative numbers, decimals, unit suffixes like deg and %, inconsistent comma and space usage, and the extra dot/period and hyphen/dash characters within the text "lin-grad.ient". Please let me know if I'm missing something. The only thing I can see that it does not handle is a badly formed decimal number like "0..8".
If you really want an array of numbers, you can convert the entire array in the same line of code:
array = whatever.match(/-?\d*\.?\d+/g).map(Number);
My particular code, which is parsing CSS functions, doesn't need to worry about the non-numeric use of the dot/period character, so the regular expression can be even simpler:
/-?[\d\.]+/g
var result = input.match(/\d+/g).join([])
Using split and regex :
var str = "fooBar0123".split(/(\d+)/);
console.log(str[0]); // fooBar
console.log(str[1]); // 0123
The answers given don't actually match your question, which implied a trailing number. Also, remember that you're getting a string back; if you actually need a number, cast the result:
item=item.replace('^.*\D(\d*)$', '$1');
if (!/^\d+$/.test(item)) throw 'parse error: number not found';
item=Number(item);
If you're dealing with numeric item ids on a web page, your code could also usefully accept an Element, extracting the number from its id (or its first parent with an id); if you've an Event handy, you can likely get the Element from that, too.
As per #Syntle's answer, if you have only non numeric characters you'll get an Uncaught TypeError: Cannot read property 'join' of null.
This will prevent errors if no matches are found and return an empty string:
('something'.match( /\d+/g )||[]).join('')
Here is the solution to convert the string to valid plain or decimal numbers using Regex:
//something123.777.321something to 123.777321
const str = 'something123.777.321something';
let initialValue = str.replace(/[^0-9.]+/, '');
//initialValue = '123.777.321';
//characterCount just count the characters in a given string
if (characterCount(intitialValue, '.') > 1) {
const splitedValue = intitialValue.split('.');
//splittedValue = ['123','777','321'];
intitialValue = splitedValue.shift() + '.' + splitedValue.join('');
//result i.e. initialValue = '123.777321'
}
If you want dot/comma separated numbers also, then:
\d*\.?\d*
or
[0-9]*\.?[0-9]*
You can use https://regex101.com/ to test your regexes.
Everything that other solutions have, but with a little validation
// value = '675-805-714'
const validateNumberInput = (value) => {
let numberPattern = /\d+/g
let numbers = value.match(numberPattern)
if (numbers === null) {
return 0
}
return parseInt(numbers.join([]))
}
// 675805714
One liner
I you do not care about decimal numbers and only need the digits, I think this one liner is rather elegant:
/**
* #param {String} str
* #returns {String} - All digits from the given `str`
*/
const getDigitsInString = (str) => str.replace(/[^\d]*/g, '');
console.log([
'?,!_:/42\`"^',
'A 0 B 1 C 2 D 3 E',
' 4 twenty 20 ',
'1413/12/11',
'16:20:42:01'
].map((str) => getDigitsInString(str)));
Simple explanation:
\d matches any digit from 0 to 9
[^n] matches anything that is not n
* matches 0 times or more the predecessor
( It is an attempt to match a whole block of non-digits all at once )
g at the end, indicates that the regex is global to the entire string and that we will not stop at the first occurrence but match every occurrence within it
Together those rules match anything but digits, which we replace by an empty strings. Thus, resulting in a string containing digits only.

Categories

Resources