Converting a number to s string in JavaScript using the + operator? - javascript

I know that if either one of my operands is a string, it should prefer string concatenation, but I get an integer.
var number = 134324;
var num_str = number + "";
console.log(num_str);

No it should not return string .. as you are printing it in console it looks like integer but try using
var number = 134324;
var num_str = number + "";
console.log(num_str);
typeof(num_str);
It will display that your answer is string ... :) hope you satisfied ..

You can use toString() method.
num_str = number.toString()

Related

Javascript getting number from string

I have a string:
var example = 'sorted-by-' + number;
Where number variable can be any positive integer. I don't know how to reverse this process, not knowing how many digits this number has. I want to get from example string a number at the end.
var outputNumber = example.substring(10);
This is the simple solution because example string always start with 'sorted-by-'.
let num = + string.substr(10);
You can use String#replace function to replace sorted-by- to empty string and after that convert left part to a number:
var example = 'sorted-by-' + 125;
var num = +example.replace('sorted-by-', '');
console.log(num);
You can split string at - and get last element using pop().
var example = 'sorted-by-' + 100.99
var n = +(example.split('-').pop())
console.log(n)
You can also use regex for this.
var number = 245246245;
var example = 'sorted-by-' + number;
var res = example.match(/^sorted-by-(\d+)/);
console.log(+res[1]);

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);

number_format function of php and calculate with js

I'm using number_format function of PHP to format: 2100000 --> 2,100,000. Everything is OK
But when I using 2,100,000 to calcutate with javascript then I got a message: NaN.
So how can I solve this problem?
Thank you very much.
You can remove the commas from the number using a Regex
var myNumber = "2,100,000";
myNumber = parseInt(myNumber.replace(/\,/g,''), 10);
console.log(myNumber);
Show the formatted number but echo the unformatted number elsewhere and use that in js. For example:
PHP
<div id="number" data-myvalue="<?=$number?>"><?=number_format($number)?></div>
JAVASCRIPT
var myvalue = $("#number").data("myvalue");
"2,100,000" is a string. You'll need to remove "," so that it can be parsed by JavaScript and used for calculations. It's better to pass numbers around without custom formatting. However, if you receive data in such format, you can deal with them like so:
var a = "2,100,000";
a = a.replace(/,/g, ""); //Replace all occurences of "," with ""
a = parseInt(a); //If you know it's an integer
a = parseFloat(a); //If it might be a float
a += 1;
alert(a); //Displays 2100001
number_format returns 2,100,000 which is a string.
If you want to make other calculations with that in js, you will have to convert it to a integer( or float depending on what you need)
var number_string = '2,100,000';
number_string = string.replace(/[^0-9]/gi, ''); // remove non-numeric charachters
var number = parseInt(number_string); // parse the string to integer
Hope this helps.
You can use a split.join combination like this:
var numStr = "2,100,000";
var num = numStr.split(',').join('');

JavaScript: How to convert an HTML string into a JavaScript number?

I have a number that I need to pull from my html:
<span>123,456.78</span>
How can I convert this string into a number that I can do math on?
var numberString = $('span').text();
var realNumber = Number(numberString); //returns NaN
A jQuery-only solution would be okay.
parseInt() or parseFloat() would just about do it.
var number = parseFloat($('span').text());
after checking and seeing this doesn't work...
try
var number =
$('span').text().replace(/([^0-9\.])/g,"");
var number = parseFloat($('span').text().replace(/([^0-9\\.])/g,""));
I'm not sure what realNumber does, but here's how I'd convert that string into a number:
var numberString = $('span').text();
var amount = + numberString.replace(/,/g, '');
This removes the commas, then uses the + unary operator to convert the string to a number. In your example, the result is the number 123456.78.
updated
var numberString = $('span').text();
var number = Number(numberString.replace(/[^0-9\.]+/g,""));

How do I cast a decimal number to String in Javascript?

325.234 to string?
is it toString()?
Simplest way, concatenate it with an empty string:
325.234 + '';
Which will implicitly call toString() on the number.
You could also use:
String(325.234);
And:
325.234.toString();
Sure, why not just:
325.234.toString()
or String(325.234)
var number = 123.54
var string = number.toString();
The "toString()" method is called implicitly when you use a non-string as part of a string concatenation. Such as:
var newString = "Hello " + number;

Categories

Resources