Remove Euro Value and money format with JQuery - javascript

I already know how to get a value from a label, the problem is that its showing something like
€123,453.28
I need to remove the eurosign and the commas to be able to make a calculation.
Not remove the decimal point of course
$(document).ready(function () {
$("#TxtVatExcluded").keypress(function () {
var invoicedAmmount = $("#MainContent_VehicleInformationControl_LblInvoicePriceValue").text();
alert(invoicedAmmount);
if (invoicedAmmount > 0) {
var ammountWithoutVat = $("#TxtVatExcluded").val();
var result = (ammountWithoutVat / invoicedAmmount) * 100;
$("#OutputLabel").html(result + " %");
}
});
});

"€123,453.28".replace(/[^\d.]/g,"") // Replace every non digit char or dot char
// With an empty string.
Live DEMO
So in your code:
var ammountWithoutVat = $("#TxtVatExcluded").val().replace(/[^\d.]/g,"");
var result = (pareseFloat(ammountWithoutVat, 10) / invoicedAmmount) * 100;

Related

js function ignores Decimal Numbers

So i made a function that calculate the price by multiplication how many meters i put the problem is when ever i put decimal numbers it ignores it
heres my script
<script>
function getFillingPrice() {
cake_prices = document.getElementById('price').value;
filling_prices = document.getElementById('test2').value;
var t=parseInt(filling_prices);
var x=parseInt(cake_prices);
return t*x;
}
function calculateTotal() {
var total = getFillingPrice();
var totalEl = document.getElementById('totalPrice');
document.getElementById('test3').value =total + " دينار ";
totalEl.style.display = 'block';
}
</script>
You're converting the values to integers when you get them from the DOM.
Change this...
var t=parseInt(filling_prices);
var x=parseInt(cake_prices);
to this...
var t=parseFloat(filling_prices);
var x=parseFloat(cake_prices);
Beside the parsing problem, you could use
an unary plus + and
a default value for non parsable value, like letters or an empty string (falsy values) with a logical OR ||.
cake_price = +document.getElementById('price').value || 0
// ^ unary plus for converting to numbner
// ^^^ default value for falsy values
Together
function getFillingPrice() {
var cake_price = +document.getElementById('price').value || 0,
filling_price = +document.getElementById('test2').value || 0;
return cake_price * filling_price;
}

Check if the decimal digits is equal to .9 using javascript

Just want to ask if how to detect numbers in decimal places using javascript?
var totalpages = {{$photos->totalphotoCount}} / {{$photos->photoCount}};
if(totalpages === to something like .9 in the decimals)
{
write a code here
}
Try this:
if(totalpages.toString().match(/.*\.9/)) {
...
}
if it does not match, it would return null
You can use regex's but if you need more advanced check you can add a helper method like this
// count specifies how many decimals you want to return
function getDecimals(number, count) {
var nString = number.toString();
var decStartIndex = nString.indexOf(".") + 1;
nString = nString.slice(decStartIndex, decStartIndex + count);
return Number(nString);
}
function myFunction() {
var num = 123.2381456;
var dec1 = getDecimals(num, 1); // returns 2
var dec1 = getDecimals(num, 0); // returns 0
var dec1 = getDecimals(num, 5); // returns 23814
}

Move comma position JavaScript

I'm trying to move the position of the comma with the use of JavaScript. I have managed to remove all the parts of the string I needed removing. The only problem is that the comma is in the wrong position.
The current outcome is 425.00, but I simply want '42.50'
success: function(result) {
if (result != '') {
alert(" "+result+" ");
}
var discountVal = result.replace(/\D/g,'');
newDiscountVal = discountVal.replace(7.50, '');
$("input#amount").val(discountVal);
}
I am grabbing database echo values with a combination of string and echo - numbers..
You could divide by ten, then convert back to a String using toFixed(2) which forces formatting of 2 decimal places
Javascript allows implicit conversion of Strings to numbers, by firstly converting the String to a Number so it is valid to divide a String by a number.
var input= "4250.00";
var output = (original / 100).toFixed(2); // => "42.50"
Note this method has different behaviour due to rounding. Consider the case 9.99. If you use a string manipulation technique you'll get ".99", with divide by 10 method above you'll get "1.00". However from what has been said in comments I believe your inputs always end .00 and never anything else, so there will be no difference in reality.
If it is number you can just divide by 10
If it is string you can do like this:
var ind = text.indexOf('.');
text = text.replace('.', '');
text.slice(0, ind-1) + '.' + text.slice(ind-1, text.length)
Here is a solution:
function moveComma(val, moveCommaByInput) {
if (val || typeof val === 'number') {
const valueNumber = Number(val);
const moveCommaBy = moveCommaByInput || 0;
if (isNaN(valueNumber)) {
return null;
} else {
return Number(`${valueNumber}e${moveCommaBy}`);
}
}
return null;
}
This is how i solved it..
var discountVal = result.replace(/\D/g, '');
var newDiscountVal = discountVal.replace(7.50, '');
var lastDigits = newDiscountVal.substr(newDiscountVal.length - 2);
var removedDigits = newDiscountVal.slice(0,newDiscountVal.length - 2);
var discountRealValue = removedDigits + '.' + lastDigits;
$("input#amount").val(discountRealValue);
Cheers

How to add spaces separating thousands in Javascript in this example

I have two functions here. One that adds a "," for separating thousands, like 1234 -> 1 234. And one function for increasing.
The function for increasing is just printing 123456 and I would like to combine these, I though I could just change:
$this.html(++current);
to:
$this.html(addSpaces(++current));
But it's not working. Please help me, how can I fix this?
function addSpaces(nStr)
{
nStr += "";
x = nStr.split(".");
x1 = x[0];
x2 = x.length > 1 ? "." + x[1] : "";
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, "$1" + " " + "$2");
}
return x1 + x2;
}
function count($this) {
var current = parseInt($this.html(), 10);
current = current + 13 /* This is increment */
$this.html(++current);
if (current > $this.data("count")) {
$this.html($this.data("count"));
} else {
setTimeout(function() { count($this); }, 100);
}
}
UPDATE I modified your jsfiddle
As current will be parsed again and again from your formatted value, we need to remove spaces from it
current = parseInt(($this.html()).split(' ').join(''), 10)
Also, you need to keep a trace of the string value of the incremented current, under a variable named nextString
You want your number grouped by, at most, 3 digits. The thing is, you may have a remainder if 3 does not divide your string's length. Once you isolate the remainder part of your string (left most) you can group all the others by 3.
DEMO
function addSpaces(nStr)
{
var remainder = nStr.length % 3;
return (nStr.substr(0, remainder) + nStr.substr(remainder).replace(/(\d{3})/g, ' $1')).trim();
}
function count($this) {
var current = parseInt(($this.html()).split(' ').join(''), 10),
nextString = (current+13) + '';
$this.html(addSpaces(nextString));
if (current > $this.data("count")) {
$this.html($this.data("count"));
} else {
setTimeout(function() {
count($this);
}, 100);
}
}
Or You could use things like toLocaleString() if that's what you want :
var number = 3500;
console.log(number.toLocaleString()); // Displays "3,500" if in U.S. English locale
var number = 123456.789;
// German uses comma as decimal separator and period for thousands
alert(number.toLocaleString("de-DE"));
// → 123.456,789
// Arabic in most Arabic speaking countries uses real Arabic digits
alert(number.toLocaleString("ar-EG"));
// → ١٢٣٤٥٦٫٧٨٩
// India uses thousands/lakh/crore separators
alert(number.toLocaleString("en-IN"));
// → 1,23,456.789
// the nu extension key requests a numbering system, e.g. Chinese decimal
alert(number.toLocaleString("zh-Hans-CN-u-nu-hanidec"));
// → 一二三,四五六.七八九
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
alert(number.toLocaleString(["ban", "id"]));
// → 123.456,789
See : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
First one works, and you can use following for second one;
<div class="count">1234</div>
And js;
$(".count").on("click", function() {
$this = $(this);
var current = parseInt($this.html(), 10);
current = current + 13 /* This is increment */
$this.html(++current);
if (current > $this.data("count")) {
$this.html($this.data("count"));
} else {
setTimeout(function() { count($this); }, 100);
}
});
Here is working demo: Demo (Click on first div on demo)

javascript variable > than number

What I am tying to find is:
"if div contains '(a number greater than 1600 x a number greater than 1063)' alert success else alert error"
if (($('div:contains("(/*number greater than 1600*/ x /*number greater than 1063*/)")').length > 0)) {
alert("SUCCESS");
}
else {
alert("ERROR");
}
I thought I could use variables like
var w > 1600
var h > 1063
and then put them in like:
$('div:contains("('+ w + 'x' + h + ')")')
but that doesn't seem to work
Any ideas?
If your goal is to find all matching divs, you have to do a bit more work. Not a lot, but a bit:
var w = 1600;
var h = 1063;
// Find all divs and filter them
var matchingDivs = $("div").filter(function() {
// Does this div's text match the form (1601 x 1064)?
// If so, grab the numbers.
var match = /^\((\d+) x (\d+)\)$/.exec($(this).text());
if (match) {
// Yes, it does, do the numbers fit?
if (parseInt(match[1], 10) > w && // [1] = the first capture group
parseInt(match[2], 10) > h) { // [2] = the second capture group
// Keep this div
return true;
}
}
// Don't keep this div
return false;
});
If a div contains a number and nothing else, you can get it like this:
var num = Number($("#myDiv").text());
Or you can use the somewhat terser unary plus:
var num = +($("#myDiv").text());

Categories