Perform calculation after adding Commas to the number - javascript

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.

Related

How do you sum two values containing the dollar sign "$"? I have been trying to figure out the methods and properties, still no clue

//for example
allInputs[22].value //equals $45 and
allInputs[4].value // equals $70
allInputs[22].value + allInputs[4].value = "$45$70"
It equals "$45$70". But I only want to sum up the value. how do I sum up both values to get the final value ignoring the dollar sign?
You can use
"$" + (parseInt(allInputs[22].value.substring(1)) + parseInt(allInputs[22].value.substring(1)))
The substring method, will get rid of the $ sign, and parseInt will convert it to a number. You need that, because if you do not use that it will concatenate the values as strings. Note that i put another set of brackets to sum the numbers. That is because, when the interpreter sees the "$" it thinks it should concatenate strings. But we want to sum the numbers and then concatenate the sum with the "$" string.
You can use reduce and check for a non-number sign at the beginning of a value:
var allInputs = ["$45","$70"];
var sum = allInputs.reduce(function(pre, curr){
if(isNaN(curr[0]))return pre+(+curr.slice(1));
return pre+curr;
},0);
console.log('$'+sum);
This is a general function expression that accepts the string value from a form input and returns a number.
const getNumber = (val) => Number(val.match(/[\d\.]+/));
You can use it like this:
const sum = getNumber(allInputs[22].value) + getNumber(allInputs[4].value);
DEMO
Note: ideally you should store the currency value ($, £, € etc) separately from the values so this doesn't become an issue.
I guess you need parseFloat(). Accordingly the following would be my helper function.
function addDollars(s1,s2){
var n1 = parseFloat(s1.replace(/[^0-9\.]/g,"")),
n2 = parseFloat(s2.replace(/[^0-9\.]/g,""));
return "$"+ (n1+n2).toFixed(2);
}
console.log(addDollars("$123.42","$12.88"));
You can use
parseFloat(allInputs[22].value.slice(1)) + parseFloat(allInputs[4].value.slice(1))
Remember that string are arrays.
if you want to end up with the "$" sign then just concatenate it.
You need to remove the "$" and convert the strings into numbers to sum them up.
Code
You can remove the "$" with replace like allInputs[22].value.replace('$', '') this will return "42" as a string.
Now we need to convert this string into a number. There are many ways to do this. I use Number() in the following solution.
Solution
var someMoney = '$50'
var moreMoney = '$60'
var toMuchMoney = "$" + Number(someMoney.replace('$', '')) + Number(moreMoney.replace('$', ''))
console.log(toMuchMoney)
To solve this, You should know about the difference between concatenation and addtion in javascript.
If you add two strings, You get concatenation of both strings as answer
"$45" + "$70" = "$45$70"
If you add two integers, you get addition.
45 + 70 = 115
So, to solve your problem, You need to first extract numbers from your variables and then do addition on them.
To extract numbers you can use any method but I am using split.
To convert string into integer you can use parseInt
let num1 = "$45";
let num2 = "$70";
function getValue(num) {
return parseInt(num.split('$')[1]);
}
let sum = getValue(num1) + getValue(num2);
console.log("$" + sum);

how to replace a string which is not integer using regex in javascript

i have use this regex try to replace a string which is not a integer ,however it replace when it is a integer.
this.v=function(){this.value=this.value.replace(/^(-?[1-9]\d*|0)$/,'');}
what is the opposite regex? :what is the regex for replace a string which is not a integer with "".
eg:if user entered string is not -2,0,1,123 such like that i want clear the input.if string like 2e3r,2.5,-1.3 the input will be clear
value
If you must use regex then the following should work. Not tested for efficiency, just thrown together.
var numbersOnly = function(number_string) {
var re = /(\+?|\-?)([0-9]+)(\.[0-9]+)*/g;
return number_string.match(re);
}
numbersOnly('pears1.3apples3.2chinesefood-7.8');
// [ '1.3', '3.2', '-7.8' ]
i have solved this one by changing the function logic:
onblur="(this.v=function(){var re=/^(-?[1-9]\d*|0)$/;if(!re.test(this.value)){this.value=''}}).call(this)
You could sanitize user input using parseInt or Number methods. For example:
var normalInput = "1";
normalInput = parseInt(normalInput, 10);
console.log(normalInput); // prints 1
var wrongInput = "12a23-24";
wrongInput = parseInt(wrongInput, 10);
console.log(wrongInput); // prints 12 (stops after first not valid number)
Or something like that:
var myInput = "21312312321",
processedInput = Number(myInput);
if(processedInput !== NaN){ // if number given is a valid number return it (also works for float input)
console.log(processedInput);
return processedInput;
}
else{ // otherwise return an empty string
return "";
}
Jsfiddle example1 example2.
To remove all non-digit characters in the string:
this.v=function(){this.value=this.value.replace(/\D+/g,'');}

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
}

Remove commas from the string using 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");

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