Javascript extracting number from string - javascript

I have a bunch of strings extracted from html using jQuery.
They look like this:
var productBeforePrice = "DKK 399,95";
var productCurrentPrice = "DKK 299,95";
I need to extract the number values in order to calculate the price difference.
(So I wend up with ≈
var productPriceDiff = DKK 100";
or just:
var productPriceDiff = 100";)
Can anyone help me do this?
Thanks,
Jakob

First you need to convert the input prices from strings to numbers. Then subtract. And you'll have to convert the result back to "DKK ###,##" format. These two functions should help.
var priceAsFloat = function (price) {
return parseFloat(price.replace(/\./g, '').replace(/,/g,'.').replace(/[^\d\.]/g,''));
}
var formatPrice = function (price) {
return 'DKK ' + price.toString().replace(/\./g,',');
}
Then you can do this:
var productBeforePrice = "DKK 399,95";
var productCurrentPrice = "DKK 299,95";
productPriceDiff = formatPrice(priceAsFloat(productBeforePrice) - priceAsFloat(productCurrentPrice));

try:
var productCurrentPrice = productBeforePrice.replace(/[^\d.,]+/,'');
edit: this will get the price including numbers, commas, and periods. it does not verify that the number format is correct or that the numbers, periods, etc are contiguous. If you can be more precise in the exact number definitions you expcet, it would help.

try also:
var productCurrentPrice = productBeforePrice.match(/\d+(,\d+)?/)[0];

var productCurrentPrice = parseInt(productBeforePrice.replace(/[^\d\.]+/,''));
That should make productCurrentPrice the actual number you're after (if I understand your question correctly).

Related

How to get the number before percentage symbol in a string?

These are some possible strings. The number percentage is always at beginning.
var string = "0.5% - corresponding something" or var string = "23% - correspondig something";
I need to get the the entire number before the percentage symbol.
I already tried some solutions in cutting the string, but the problem is that the number doesn't have always the same length.
Can you help me?
There are several solutions. For example:
let antani = "23% - correspondig something";
// using parseFloat
console.log(parseFloat(antani));
// using split
console.log(antani.split("%")[0]);
first split string using '%'
<script>
var str = "0.5% - corresponding something";
var res = str.split("%");
number=res[0];
console.log(res[0]);
</script>
Using Regular expression you can match the numbers (including dots) before the percentage sign.
Example:
var text = "0.5% - corresponding something";
var percentageRegex = /([0-9\.]+).+/;
var matches = percentageRegex.exec(text);
console.log(matches[1]);

ParseFloat not working

i am trying to parse a float in javascript in this way:
var number = '25.492.381';
var cost = parseFloat(number);
This returns 25.492
I wish this would return 25.492.381
How can this be done?
Remember that . in standard notation split the Integer and Fractional part of the number. You could want this:
var number = '25.492.381'.replace('.', '').replace(",",".") ;
var cost = parseFloat(number);
25.492.381 is not a float. You need to use a formatter.
Check Numbro

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

javascript - get two numbers from a string

I have a string like:
text-345-3535
The numbers can change.
How can I get the two numbers from it and store that into two variables?
var str = "text-345-3535"
var arr = str.split(/-/g).slice(1);
Try it out: http://jsfiddle.net/BZgUt/
This will give you an array with the last two number sets.
If you want them in separate variables add this.
var first = arr[0];
var second = arr[1];
Try it out: http://jsfiddle.net/BZgUt/1/
EDIT:
Just for fun, here's another way.
Try it out: http://jsfiddle.net/BZgUt/2/
var str = "text-345-3535",first,second;
str.replace(/(\d+)-(\d+)$/,function(str,p1,p2) {first = p1;second = p2});
var m = "text-345-3535".match(/.*?-(\d+)-(\d+)/);
m[1] will hold "345" and m[2] will have "3535"
If you're not accustomed to regular expressions, #patrick dw's answer is probably better for you, but this should work as well:
var strSource = "text-123-4567";
var rxNumbers = /\b(\d{3})-(\d{4})\b/
var arrMatches = rxNumbers.exec(strSource);
var strFirstCluster, strSecondCluster;
if (arrMatches) {
strFirstCluster = arrMatches[1];
strSecondCluster = arrMatches[2];
}
This will extract the numbers if it is exactly three digits followed by a dash followed by four digits. The expression can be modified in many ways to retrieve exactly the string you are after.
Try this,
var text = "text-123-4567";
if(text.match(/-([0-9]+)-([0-9]+)/)) {
var x = Text.match(/([0-9]+)-([0-9]+)/);
alert(x[0]);
alert(x[1]);
alert(x[2]);
}
Thanks.
Another way to do this (using String tokenizer).
int idx=0; int tokenCount;
String words[]=new String [500];
String message="text-345-3535";
StringTokenizer st=new StringTokenizer(message,"-");
tokenCount=st.countTokens();
System.out.println("Number of tokens = " + tokenCount);
while (st.hasMoreTokens()) // is there stuff to get?
{words[idx]=st.nextToken(); idx++;}
for (idx=0;idx<tokenCount; idx++)
{System.out.println(words[idx]);}
}
output
words[0] =>text
words[1] => 345
words[2] => 3535

Categories

Resources