Reputation: 4009
So I am trying to convert the .text()
of a div into a number that can be used for some math within the JS (currency conversion). I am gathering the text content of a div which contains items such as currency symbols as well as a decimal point which is always followed by 00
For example if the div contained £35,000.00
I am trying to get it to return 35000
not 3500000
.
I have got some RegExp that only allows use of numbers 1-9 and therefore removes the £ sign but it also takes the decimal point out, thus multiplying the number I want by 100.
This is my code:
var thisDiv = $(this);
var amount = $( this ).text().replace(/[^0-9]/gi, '');
Is there any way to ignore the numbers that come after the dot other than just dividing my variable by 100?
Upvotes: 0
Views: 1393
Reputation: 668
no need to convert to string and split and get the 0 index just do
.toFixed();
Like:
const num = 34.434343;
num.toFixed();
Upvotes: 0
Reputation: 626794
You can restrict what you match with [^0-9]
using a (?!\.\d+$)
negative lookahead:
/(?!\.\d+$)[^0-9]/g
^^^^^^^^^^
See the regex demo
The pattern means: match any non-digit if it is not a literal .
followed with 1+ digit up to the end of the string.
var re = /(?!\.\d+$)[^0-9]/g;
var str = '£35,000.00';
var result = str.replace(re, '');
document.body.innerHTML = result;
Upvotes: 0
Reputation: 2195
Extending on Mark's answer, you can the digits number before and after the decimal with the following:
numberString.toString().split(".")[0]; //before
numberString.toString().split(".")[1]; //after
Upvotes: 0
Reputation: 653
/[^0-9\.]/
this regex will keep 0-9 and .
However, it will also allow values like 1.2.3 (multiple dots)
if you want more validation than that, you might want to take a couple steps
var numberString = value.replace(/[^0-9\.]/gi, '');
if (isNaN(numberString )) {
console.log('invalid');
} else {
//parse number and use it
}
Upvotes: 3