JavaScript: Retrieve negative floating point number from string of mutiple sums - javascript

I have a simple app that allows me to caculate the total amount invoiced and deposited in a route. However I want to allow the user to input multiple values in a single input field; e.g:
500+50+36.5-45.2-10.
I have written a function that will retrieve this input and then split this string into elements of an array at the + sign and immediately parse the values to numbers and then add them and return the total the user inputs into each individual field. This is all well as long as the user does no use any sign other than +.
I have searched the use of regexp:
regular expression in javascript for negative floating point number result stored in array
Javascript Regular expression to allow negative double value?
but none of the results seem to work.
How could I make my code retrieve the values so that the negative values get passed into the array as negative values?
Here is a snippet of my Js code:
For the full code, visit my fiddle.
totalInvoiced: function () {
var a = A.invoiced.value;
var value1Arr = [];
value1Arr = a.split("+").map(parseFloat);
var value1 = 0;
value1Arr.forEach(function (value) {
value1 += value;
});

I really like PhistucK's solution, but here an alternative with regex:
value1Arr = a.split(/(?=\+|\-)/);
This will split it, but keeps the delimiter, so the result will be:
["500", "+50", "+36.5", "-45.2", "-10"]

A bit dirty, but maybe a.replace(/-/g, "+-").split("+"), this way, you add a plus before every minus, since the negative numbers just basically lack an operator.

You can use this pattern that splits on + sign or before - sign:
var str = '500+50+36.5-45.2-10';
console.log(str.split(/\+|(?=-)/));

Related

I need to simplify a string without actually changing the numbers (positive and negative signs, parentheses, etc.)

I am creating a program that needs to have a way of "doctoring" a numerical equation. It needs to be able to simplify to the numbers and the basic numerical equation, without extra parentheses and negative and positive signs. Example:
var input = '[doctor] 2+-(-(2))'
var doctorPositive = input.search('[doctor]')
if (doctorPositive > -1) {
var deleteDoc = input.replace('[doctor]', '')
// Code here
document.getElementById('output').innerHTML = doctored;
}
I need deleteDoc which is currently equal to;
'2+-(-(2))'
to become:
'2+2"
I need this to work for almost any numerical equation. It cannot change any variables within the equation however. I don't know where to start.
This looks a lot like homework.
This will work for the 1 input you provided and probably a few other simple strings:
'2+-(-(2))'.replaceAll('(', '').replaceAll(')', '').replaceAll('--', '+').replaceAll('++', '+')

Regular expression for decimals

Hi Experts,
I have a requirement where I think regular expressions might help reducing a lot of if statements and conditions in my code.
My requirement is something like this
I have a quantity field that is displayed in the UI( JavaScript) which has a control factor (based on the quantity field's Unit of Measurement) send from the backend .
Example my Quantity = "126.768"
The control factor D = "2" (which means the number of display positions after the decimal point is 2) .
Now I need a regex to find the following
Regex1 should check whether the quantity is having any decimal points at all. If so then it should check whether the value after decimal points are not just zeros (ex sometimes quantity comes without getting formatted with the full length of decimal points 145.000, which in our case should be displayed as 145 in the UI and the control factor D doesn't need to be considered). Also RegEx should consider quantity values like ".590" ".001" etc.
Since I am new to RegEx I am struggling to come up with an expression
I managed to make a very basic RegEx that just check for the "." within the quantity and all the values after the "."
RegEx = /[.]\d*/g
If RegEx1 returns a positive result . Then Regex2 should now check for the value D. It should adjust the decimal points based on D. For example if D = 3 and quantity = 345.26 then the output of regex2 should give 345.260 and similarly is D = 1 then quantity should be 345.3 ( donno whether rounding is possible using RegEx, a solution without rounding is also fine).
Regards,
Bince
The first regex is
"\d*\.\d*[1-9]\d*"
It searches for at least 1 non-zero digit after the dot.
For the second point, you can round with regex only if the digits overcomes the control factor, while for the 0-padding you can't use regex:
function round(num, control) {
var intPart = num.split(".")[0];
var decPart = num.split(".")[1];
decPart = decPart.substring(0, control); //this does the truncation
var padding = "0".repeat(control - decPart.length); //this does the 0-padding
return intPart + "." + decPart + padding;
}
var num1 = "210.012";
var num2 = "210.1";
var control = 2;
console.log(round(num1, control));
console.log(round(num2, control));
You shouldn't need for any check or regex,
there is a Number.prototype.toFixed method that will help you to adjust decimals.
It basically rounds a number to the nearest decimal point and returns a string. If you're working with strings, make sure you cast it before (using Number statically)
console.log(17.1234.toFixed(2)); // round it down
console.log(17.1264.toFixed(2)); // round it up
console.log(17..toFixed(2)); // Integer
console.log(Number("126.768").toFixed(2)); // from string casting

Converting Strings to Integer and get the persentage of two number

What I'm trying to do is to make a progress bar for donation. My html structure is:
<div class="hgoal" style="text-align: center;">My goal is to raise $<span id="mygoal">9,999.00</span></div>
<div class="donation-total">Total Donation<span id="total-donation">1,000.00</span></div>
my javascript so far is to get the innerHTML value of mygoal and total-donation.
var mygoal = document.getElementById("mygoal").innerHTML;
var totalgoal = document.getElementById("total-donation").innerHTML;
and I'm getting this as a result:
mygoal = "9,999.00";
total-donation = "1,000.00";
I believe this is a string and not an integer, and using parseInt() only give me the first digit number.
Can anyone give me an idea how can I make this into an integer that can use for computation? example:
mygoal + total-donation = 10,999.00
And also, any idea how can i get the percentage of this two varible?
Use .replace(/,/g,'') to replace commas, then you get the magic of type coercion to convert your string to a number during calculation...
var mygoal = document.getElementById("mygoal").innerHTML.replace(/,/g,'');
var totalgoal = document.getElementById("total-donation").innerHTML.replace(/,/g,'');
If you use + on strings, they will be appended to each other, but other mathematical operators (*/- etc...) will first coerce the strings into numbers. To force coercion, you can multiply by 1, or perhaps use Number("123123.123")...
Number(mygoal) + Number(totalgoal); // using addition, so coerce strings to numbers
(mygoal / total_donation) * 100; // does not need coercion
Your main issue is, that your numbers include colons. The parseFloat() call will work, once you replace these colons. You may use the following code to do so:
// define regexp to replace colons
var replaceColons = new RegExp(',', 'g');
// apply regex
num = num.replace(replaceColons, '');
mygoal=parseInt(mygoal.replace(/,/gi,"")) will give you mygoal=9999.
You should use parseFloat(), not parseInt() ...
More, you have to remove the commas from the string, since parseFloat() does not undertsand number formatting characters (like comma). So, for example:
mygoal = mygoal.replace(/,/g, '');
total_donation = total_donation.replace(/,/g, '');
To get the percentage of two numbers, use:
(mygoal / total_donation) * 100;
Note that in JavaScript you can't use 'minus' char (-) in variables names.
You could use for example 'underscore' char (_), or CamelCase, wich is the recommended style for variables in JavaScript.
You need to convert those Indian (maybe) numbers to valid Javascript numbers for the sum, then convert the output back to the initial format using Number.toLocaleString.
var mygoal = "9,999.00";
var total_donation = "1,000.00";
var total = Number((Number(mygoal.replace(/,/g, '')) + Number(total_donation.replace(/,/g, ''))).toFixed(2));
var finalResult = total.toLocaleString('en-IN',{minimumFractionDigits: 2 });
alert(finalResult);

How to round a number up and add numeric punctuation

I've got the following pen: http://codepen.io/anon/pen/LVLzvR
I cant quite figure out how to round the number up so you don't break the punctuation. I need to round the number up as I don't want to see a value like 33,333.,333
//ADDS PUNCTUATION EVERY THREE CHARACTERS
$('input.numericpunctuation').keyup(function(event){
var oNum= $(this).val(); // USE THIS NUMBER FOR CALCULATION
var num = oNum.replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
console.log(num2);
console.log(oNum);
// the following line has been simplified. Revision history contains original.
$(this).val(num2);
});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
Example input event:
If I input 5555, is expect to see (and do see) 5,555. However if I add 5555.55 I get 5,555,.55. Ideally id like to round the number up removing the decimal.
The problem isn't just with decimals, you will get the wrong formatting also by entering non digits, e.g., clicking King Kong will result in Kin,g K,ong. So, what you probably want is to filter out non-digits, which can be done by changing the line var oNum= $(this).val(); to:
var oNum= $(this).val().match(/\d/g).join('');
The value inside the match function is a RegEx object - if you never used it before then congratulations!

Read a number value from a div element and round to 2 decimal places

I want to retrive a number value from a div and then round that number to 2 decimal places using jQuery.
So far I have the element name and value:
<div class="value">Price = £133.3223443</div>
I am using the toFixed() method to convert a number into a string then round to 2 decimal places:
var inNum = 12345.6789;
inNum.toFixed(2);
However, I am having trouble trying to read a number within the element on the page (ignoring 'Price'), rather than just rounding a number entered within the jQuery.
Parse it with regexp? :)
http://jsfiddle.net/LERFB/2/ <--- working fiddle
var price = $('div.value').text();
var parsedPrice = parseFloat(price.replace(/([^0-9\.])/g, ''));
alert(parsedPrice.toFixed(2));
You can use text() to get the value from the element, and the split() by £ to get the numerical price. Try this:
var inNum = parseFloat($('.value').text().split('£')[1]).toFixed(2);
Example fiddle
Obviously you will also need some form of verification to ensure that there is a £ character in the string to split by, and that the value retrieved is numerical.
The following regular expression will extract the floating numbers from the string and do a toFixed operation.
var inNum = parseFloat($(".value").text().match(/[\d\.\d]+/i)).toFixed(2);
Please make sure you have the value inside the container all the time.

Categories

Resources