Converting Strings to Integer and get the persentage of two number - javascript

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

Related

parseInt fixing the value

Here I have a value with commas.
Ex:-var abc = "10,10.12";
If I use var x = parseInt(abc);
it is returning 10
Expected output is 10,10.12
as I have used ng-value="UpdatedPropuesta.VALOR_CUOTA | number:2" in JSP.
If you want an array of numbers out of the string then try this,
const input = "10,10.12";
var output = input.split(",");
output = output.map(i => Number(i));
console.log(output);
10,10.12
That is not the number 1010.12, it is the number 10, a comma operator, and the number 10.12.
Commas are not part of the JavaScript literal syntax.
However, in your case you're passing two arguments to parseInt, the first should be a string to convert (but JS will convert it to a strign) and the second is the radix – the number base – which should be an integer.
So JS's type conversion will lead to:
var x = parseInt('10', 10);
Which is of course 10.
After question update
var x = parseInt("10,10.12");
As comma are not part of JS numeric literals, the parse will stop at the comma because it is not a character that can appear in a number.
So the answer is still 10.

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

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(/\+|(?=-)/));

Javascript convert string to integer

I am just dipping my toe into the confusing world of javascript, more out of necessity than desire and I have come across a problem of adding two integers.
1,700.00 + 500.00
returns 1,700.00500.00
So after some research I see that 1,700.00 is being treated as a string and that I need to convert it.
The most relevant pages I read to resolve this were this question and this page. However when I use
parseInt(string, radix)
it returns 1. Am I using the wrong function or the an incorrect radix (being honest I can't get my head around how I decide which radix to use).
var a="1,700.00";
var b=500.00;
parseInt(a, 10);
Basic Answer
The reason parseInt is not working is because of the comma. You could remove the comma using a regex such as:
var num = '1,700.00';
num = num.replace(/\,/g,'');
This will return a string with a number in it. Now you can parseInt. If you do not choose a radix it will default to 10 which was the correct value to use here.
num = parseInt(num);
Do this for each of your string numbers before adding them and everything should work.
More information
How the replace works:
More information on replace at mdn:
`/` - start
`\,` - escaped comma
`/` - end
`g` - search globally
The global search will look for all matches (it would stop after the first match without this)
'' replace the matched sections with an empty string, essentially deleting them.
Regular Expressions
A great tool to test regular expressions: Rubular and more info about them at mdn
If you are looking for a good tutorial here is one.
ParseInt and Rounding, parseFloat
parseInt always rounds to the nearest integer. If you need decimal places there are a couple of tricks you can use. Here is my favorite:
2 places: `num = parseInt(num * 100) / 100;`
3 places: `num = parseInt(num * 1000) / 1000;`
For more information on parseInt look at mdn.
parseFloat could also be used if you do not want rounding. I assumed you did as the title was convert to an integer. A good example of this was written by #fr0zenFry below. He pointed out that parseFloat also does not take a radix so it is always in base10. For more info see mdn.
Try using replace() to replace a , with nothing and then parseFloat() to get the number as float. From the variables in OP, it appears that there may be fractional numbers too, so, parseInt() may not work well in such cases(digits after decimal will be stripped off).
Use regex inside replace() to get rid of each appearance of ,.
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = a+b;
This should give you correct result even if your number is fractional like 1,700.55.
If I go by the title of your question, you need an integer. For this you can use parseInt(string, radix). It works without a radix but it is always a good idea to specify this because you never know how browsers may behave(for example, see comment #Royi Namir). This function will round off the string to nearest integer value.
var a = parseInt('1,700.00'.replace(/,/g, ''), 10); //radix 10 will return base10 value
var b = parseInt('500.00'.replace(/,/g, ''), 10);
var sum = a+b;
Note that a radix is not required in parseFloat(), it will always return a decimal/base10 value. Also, it will it will strip off any extra zeroes at the end after decimal point(ex: 17500.50 becomes 17500.5 and 17500.00 becomes 17500). If you need to get 2 decimal places always, append another function toFixed(decimal places).
var a = parseFloat('1,700.00'.replace(/,/g, ''));
var b = parseFloat('500.00'.replace(/,/g, ''));
var sum = (a+b).toFixed(2); //change argument in toFixed() as you need
// 2200.00
Another alternative to this was given by #EpiphanyMachine which will need you to multiply and then later divide every value by 100. This may become a problem if you want to change decimal places in future, you will have to change multiplication/division factor for every variable. With toFixed(), you just change the argument. But remember that toFixed() changes the number back to string unlike #EpiphanyMachine solution. So you will be your own judge.
try this :
parseFloat(a.replace(/,/g, ''));
it will work also on : 1,800,300.33
Example :
parseFloat('1,700,800.010'.replace(/,/g, '')) //1700800.01
Javascript doesn't understand that comma. Remove it like this:
a.replace(',', '')
Once you've gotten rid of the comma, the string should be parsed with no problem.

Plus operator problems in Jquery

I was trying with following script
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#item1_number_1').keyup(function() {
var valone = $('#item1_number_1').val();
var valtwo = 5;
var total = ((valone) + (valtwo));
$('#item2_number_1').val(total.toFixed(2));
});
});
</script>
I do not get any result in the field. But when I assign multiple (*) instead of plus (+), I am getting result.
I cannot understand what the error is in "var total = ((valone) + (valtwo));"
You can only call toFixed on Numbers.
String * String will convert the strings to Numbers and multiply them giving you a Number.
String + String will concatenate the two Strings together giving you a String.
You need to convert the strings to Numbers manually before you try to add them together.
var total = (+valone) + (+valtwo);
Then Number + Number will add the two Numbers together giving you a Number.
The value of an input is always a string. "Adding" a string concatenates, giving another string. Strings do not have a toFixed method.
* however is unambiguously "multiply", giving a number and therefore a result.
var valone = parseFloat(document.getElementById('item1_number_1').value);
Use parseInt() to convert fetched value(valone ) to number, and calculate, something like this, please use this only when your number is not float(56.66),
var valone = parseInt($('#item1_number_1').val(), 10);
var valtwo = 5;
var total = ((valone) + (valtwo));
The fetched vaue is treated like string until you convert it into number.
UPDATE
After Archer pointed out, I came to know you are using toFixed() method, which supposed to expect float numbers. So in this case you should use parseFloat() as given below.
var valone = parseFloat($('#item1_number_1').val());
I think one of them is a string. Try parseInt(valone) to make it an int first.
The issue is the + operator can also be used to concat strings together. The * operator is ONLY for multiplication and therefore it implicitly converts your values to numbers.
So you either need to use parseInt, parseFloat, or Number to explicitly convert to a numeric type before using the + operator.

Javascript is treating variables as Strings, why?

I have the variable y, which is a subtotal. Its value is different depending on what happens with the html, but throughout the script I declared it like this:
var y = 21.78;
etc. Why is it that on my last equation where I add up the total, it treats them as strings when I want to add the values?
var tax = (0.055*y).toFixed(2);
var totalprice = y+tax;
/* totalprice holds "21.781.20" instead of 22.98 */
According to:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number/toFixed
toFixed() returns:
A string representation of number that does not use exponential
notation and has exactly digits digits after the decimal place.
thus, y+tax is cast to a string since one of the operands is a string.
In my opinion, this would make sense as Javascript's intrinsic numeric types do not have the ability to store a specific number of decimal place digits, so a string would be the most appropriate data structure to store this with.
I would advise you do all your addition before calling toFixed(), since the method is most suitable for formatting display output.
var taxRate = 0.055;
var subtotal = 21.78;
var tax = (taxRate * subtotal).toFixed(2),
totalprice = ((1+taxRate) * subtotal).toFixed(2);
document.write(totalprice);
The .toFixed() method returns a string. Try applying that method as the last step after all other calculations.
Here's a simple fix. Put '+' in front of the tax variable to convert it to a number.
var y = 21.78;
var tax = (0.055*y).toFixed(2);
var totalprice = y+ (+tax);
totalprice === 22.98;
If you don't want any rounding errors when you use toFixed, then include this re-implementation of it in your script.
http://bateru.com/news/2012/03/reimplementation-of-number-prototype-tofixed/
In my experience, if there's any chance available, Javascript will see the "+" sign as concatenate rather than addition. It's driven me nuts on more than one occasion. I will generally do this rather than chance concatenation:
var totalprice = parseInt(y)+parseInt(tax);
When letter replaces value, multiply with 1 when you're in need of +.
var totalprice = (y*1) + tax .
Other operands work fine, it's just the + operand that needs special treatment when variable replace value.

Categories

Resources