This question already has answers here:
Javascript: Converting String to Number?
(4 answers)
Closed 4 years ago.
How to convert "4,250,000.40" to 4,250,000.40 that is converting string to number by remaining the commas and dots? using JavaScript
You can use parseFloat(str) to convert a string to a number, but first you need to remove the commas from the string, as parseFloat doesn't work for numbers with commas in them.
parseFloat(str.replace(/,/g, ""));
var str = "4,250,000.40";
str = str.replace(/\,/g, "")
console.log(str)
console.log(parseFloat(str).toFixed(2))//to always show 2 decimal places
You can't directly convert "4,250,000.40" to a number in vanilla JS, let alone preserve commas. 4,250,000.40 is not a valid number in JavaScript, because a comma is an illegal character in a Number.
you can use regex to delete commas, then use Number.parseFloat(), but then number formatting is lost. Instead, I suggest using a number formatting library like Numeral.js. To convert "4,250,000.40" to a numeral you'd use:
const num = numeral("4,250,000.40");
you can reformat your number using the format() method like so:
const formatedNum = numeral("4,250,000.40").format('0,0.00');
console.log(formatedNum); // "4,250,000.40"
Here's a working example, including more cool formatting:
const num = numeral("4,250,000.40");
const formatedNum = num.format('0,0[.]00');
console.log(formatedNum); // "4,250,000.40"
// you can format number as money
console.log(num.format('$0,0[.]00')); // $4,250,000.40
// you can use abbreviations like k or m
console.log(num.format('$0.00a')); // $4.25m
// you can use financial notation
console.log(numeral("-4,250,000.40").format('($0,0)')); // ($4,250,000)
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script>
Related
This question already has answers here:
Convert currency to decimal number JavaScript
(3 answers)
Closed 9 months ago.
How to convert R$ 800,000.00 in string type to 800000 decimal type using JavaScript?
Why don’t you just use
currenyValueInt = parseInt(currencyValueString.split(" ")[1])
You sanitize the string by replacing everything but digits and the decimal separator and then cast it to a Number, either with Number() or by simply adding a + in front of the expression:
let str = +"R$ 800,000.00".replace(/[^\d.]/g, '');
console.log(str, typeof str)
This question already has answers here:
Is there a JavaScript function that can pad a string to get to a determined length?
(43 answers)
Closed 6 years ago.
Take this IP address:
192.168.1.1
I want to break it down into 4 full binary octets, so:
11000000 . 10101000 . 00000001 . 00000001.
All of the conversions I know, and those that I've found on other stackoverflow questions, only return the binary number itself, for example:
(1 >>> 0).toString(2) returns 1 when I want 00000001
Number(2).toString(2) returns 10 when I want 00000010
Is there an in-built javascript method that I haven't come across yet or do I need to manually add the 0's before depending on the number?
You can use Number#toString method with radix 2 for converting a Number to corresponding binary String.
var str = '192.168.1.1';
console.log(
// Split strings based on delimiter .
str.split('.')
// iterate over them
.map(function(v) {
// parse the String and convert the number to corresponding
// binary string afterwards add preceding 0's
// with help of slice method
return ('00000000' + Number(v).toString(2)).slice(-8)
// rejoin the string
}).join('.')
)
The simplest solution is to prefix the answer with zeros and then use a negative substring value to count from the right, not the left...
alert(("00000000" + (1 >>> 0).toString(2)).substr(-8));
This question already has answers here:
Evaluating a string as a mathematical expression in JavaScript
(26 answers)
Closed 7 years ago.
Hey guys i want to extract/evaluate the answer 2/4 in a string even ehen doing Number ("2/4") it gives me NaN as a result which is fairly reasonable! So my question is how can i evaluate this fraction from a string?
You can do eval("2/4"), which will properly result in 0.5.
However, using eval is a really bad idea...
If you always have a fraction in format A/B, you can split it up and compute:
var s = "11/47";
var ssplit = s.split('/');
document.body.innerText = ssplit[0] / ssplit[1];
Note that Division operator / will implicitly cast strings "11" and "47" to 11 and 47 Numbers.
You are looking for eval. Note
parseFloat("2/4")
2
parseFloat("4/2")
4
eval("4/2")
2
eval("2/4")
0.5
function myFunction() {
var str = "3/4";
var res = str.split("/");
alert(parseFloat(res[0]/res[1]));
}
Try with eval function :
eval("2/4");
Parsing the string only valid for numbers like 0-10 and a decimal (.) and all other if included will then result in NaN.
So, what you can do is like this:
Number(2/4)//0.5
parseFloat(2/4)//0.5
Number('2')/Number('4');//0.5
parseFloat('2')/parseFloat('4');//0.5
Number('2/4');//NaN as / is not parsable string for number
parseFloat('2/4');//2 as upto valid parsable string
parseFloat('1234/4');//1234
So, you can split string then use that like #Yeldar Kurmangaliyev answered for you.
(function(str){
var numbers = str.split("/").map(Number);
return numbers[0] / numbers[1];
})("2/4")
Keep in mind this does not check for invalid input.
This question already has answers here:
How can I extract a number from a string in JavaScript?
(27 answers)
Closed 9 years ago.
I have a string likes
AA-12,AB-1,AC-11,AD-8,AE-30
I want to get number only from this string likes
12,1,11,8,30
How can I get this using JavaScript ? Thanks :)
Use a regex, eg
var numbers = yourString.match(/\d+/g);
numbers will then be an array of the numeric strings in your string, eg
["12", "1", "11", "8", "30"]
Also if you want a string as the result
'AA-12,AB-1,AC-11,AD-8,AE-30'.replace(/[^0-9,]/g, '')
var t = "AA-12,AB-1,AC-11,AD-8,AE-30";
alert(t.match(/\d+/g).join(','));
Working example: http://jsfiddle.net/tZQ9w/2/
if this is exactly what your input looks like, I'd split the string and make an array with just the numbers:
var str = "AA-12,AB-1,AC-11,AD-8,AE-30";
var nums = str.split(',').map(function (el) {
return parseInt(el.split('-')[1], 10);
});
The split splits the string by a delimiter, in this case a comma. The returned value is an array, which we'll map into the array we want. Inside, we'll split on the hyphen, then make sure it's a number.
Output:
nums === [12,1,11,8,30];
I have done absolutely no sanity checks, so you might want to check it against a regex:
/^(\w+-\d+,)\w+-\d+$/.test(str) === true
You can follow this same pattern in any similar parsing problem.
This question already has answers here:
Parsing an Int from a string in javascript
(3 answers)
Closed 9 years ago.
How do you filter only the numbers of a string?
Example Pseudo Code:
number = $("thumb32").filternumbers()
number = 32
You don't need jQuery for this - just plain old JavaScript regex replacement
var number = yourstring.replace(/[^0-9]/g, '')
This will get rid of anything that's not [0-9]
Edit: Here's a small function to extract all the numbers (as actual numbers) from an input string. It's not an exhaustive expression but will be a good start for anyone needing.
function getNumbers(inputString){
var regex=/\d+\.\d+|\.\d+|\d+/g,
results = [],
n;
while(n = regex.exec(inputString)) {
results.push(parseFloat(n[0]));
}
return results;
}
var data = "123.45,34 and 57. Maybe add a 45.824 with 0.32 and .56"
console.log(getNumbers(data));
// [123.45, 34, 57, 45.824, 0.32, 0.56];
Not really jQuery at all:
number = number.replace(/\D/g, '');
That regular expression, /\D/g, matches any non-digit. Thus the call to .replace() replaces all non-digits (all of them, thanks to "g") with the empty string.
edit — if you want an actual *number value, you can use parseInt() after removing the non-digits from the string:
var number = "number32"; // a string
number = number.replace(/\D/g, ''); // a string of only digits, or the empty string
number = parseInt(number, 10); // now it's a numeric value
If the original string may have no digits at all, you'll get the numeric non-value NaN from parseInt in that case, which may be as good as anything.