Is it me or i can't sum these? - javascript

Good morning / Afternoon / evening :).
i have two integers that i want to turn them floats, with 4 decimal numbers to use them on GPS coordinates:
var z = y.toFixed(4);
var p = x.toFixed(4);
But there are a situation that is bugging me, that is the sum between these 'z' and 'p':
var t = z + p;
After this instruction, i want to print the result on the screen with some common functions like:
document.write(z); document.write("<br />");
document.write(t);
document.write("<br />");
document.write("<br />");
The result that i get is:
0.0000
0.0000300.0000
1.0000
1.0000300.0000
2.0000
2.0000300.0000
But what i really want is:
300.0000
301.0000
302.0000
How can i sum 'z' and 'p', after all? :S
Noob question, i know :S.
Kind regards,
Sam

That's because .toFixed() returns a String object rather than a Number, so the + operator performs concatenation.
Instead you should perform the addition of the actual numbers first and then perform .toFixed() to "round" the result for display.
var t = (x + y).toFixed(4);
document.write(t);

I think what you want is :
var t = x + y;
var p = t.toFixed(4);
document.write(p);

try this
var t = (x + y).toFixed(4);
fiddle here

The JavaScript method toFixed converts your number into a string. Thus, when you perform operation z + p it actually is string concantenation and not addition of numbers. You may first add your numbers and afterwards apply toFixed.

toFixed() returns a string, which means you are concating string when you use var t = z + p. You need to first sum your coordinates and then call toFixed().

How much is p? Are you concatenating strings?
Try with var t = parseFloat(z) + parseFloat(p);

Related

How to keep the zero's when parsing two strings to a float value

I'm trying to create a function that converts two strings to a float value.
Some external party created a theme with a backend where you should provide to values for a price:
priceBeforeComma
priceAfterComma
In the html this converts to:
<span>55,<sup>07</sup></span>
I need to do some calculations with the price as a float before splitting it up again for the html like you can see above.
I have a function that works pretty fine:
function parsePrice(price, priceDecimal) {
return parseFloat(price + "." + priceDecimal);
}
However, the problem I'm facing is that let's say I provide 07 as the decimal like above, the leading zero is removed, returning 55,7.
There is quite a big difference between 55,07 and 55,7. I expect to get back the zero as well like 55,07.
Any help will be much appreciated.
Your Code is right
function parsePrice(price, priceDecimal) {
return parseFloat(price + "." + priceDecimal);
}
parsePrice("55", "07");
if you send parsePrice("55","07") so you do not need to divide it by 100 because maybe you send it 007 then you should divide it by 1000. But your code will work properly if send string
Floats represent 07 as 07.0, so to get this to work correctly you'll need to write it as 0.07.
Here's what worked for me:
function parsePrice(price, priceDecimal) {
return parseFloat(price + priceDecimal);
}
var output = parsePrice(57, 0.07);
document.getElementById("test").innerHTML = output.toString().replace(".", ",");
<p id="test"></p>
This might be overkill, but you could use something that provides complete control over how numbers are converted to strings, and vice versa, for example: https://github.com/alexei/sprintf.js I have not used that library, but it promises to provide the same functionality as C printf, which would allow you to keep leading zeros. See the answer to the "C" language question here: Printing leading 0's in C?
(But, as an aside, also see my comment above - generally it's better to do financial calculations in integer arithmetic rather than floating point.)
So my suggestion would be to do this instead:
function price(dollars, cents) { // adjust for your currency
return parseInt(dollars)*100 + parseInt(cents);
}
function dollarsAndCents(price) {
let sign = "+";
if (price<0) {
sign = "-";
price = -price;
}
let cents = price % 100;
let dollars = (price-cents)/100;
dollars = dollars.toString();
cents = cents.toString();
if (cents.length<2) cents = "0" + cents;
return {sign: sign, dollars: dollars, cents: cents}
}
let price1 = price ("55", "07");
let price2 = price ("99", "99");
let total = price1 + price2;
console.log(dollarsAndCents(total))
//{ sign: '+', dollars: '155', cents: '06' }
let refund = -12345
console.log(dollarsAndCents(refund))
//{ sign: '-', dollars: '123', cents: '45' }
There you go, that's a pretty complete solution! Even handles negative amounts.
You should pass in Strings to your function instead by putting quotes around your numbers. Using numbers will always have the caveat of removing any leading zeroes.
function parsePrice(price, priceDecimal) {
return parseFloat(price + "." + priceDecimal);
}
parsePrice("55", "07");
Why not parse them separately as integers and add them together in the right proportions?
function parsePrice(price, priceDecimal) {
return parseInt(price) + (parseInt(priceDecimal) / 100);
}
console.log(parsePrice("55", "07"));

Add two numbers in JavaScript function

I am a beginner in JavaScript. Our teacher asked us to write a program to add two numbers using function add(). The question is shown as follows.
However, when I use my code to add the two numbers. The result is not a number.
<html>
<head> <title> Third example </title>
<script type="text/javascript">
function sum (x,y)
{ num1=parseInt(x);
num2=parseInt(y);
return (num1+num2);}
var input1 = window.prompt("Enter a number: ", 0);
var input2 = window.prompt("Enter another number: ", 0);
var input3 = window.prompt("Enter another number: ", 0);
var value1 = parseFloat(input1 + input2);
var value3 = parseFloat(input3);
var sum = sum(value1 + value3);
document.writeln("<h1> First number: " + value1 + "</h1>");
document.writeln("<h1> Second number: " + value3 + "</h1>");
document.writeln("<h1> Sum: " + sum + "</h1>");
</script>
<head>
<body></body> </html>
Why the sum is not a number?
You have to add parseFloat() separately for input1 and input2 when you calculate the sum for value1. Another change is the var sum = sum1(value1 , value3); instead of var sum = sum1(value1 + value3); which makes the parameter y of sum(x,y) as undefined.
var input1 = window.prompt("Enter a number: ", 0);
var input2 = window.prompt("Enter another number: ", 0);
var input3 = window.prompt("Enter another number: ", 0);
var value1 = parseFloat(input1) + parseFloat(input2);
var value3 = parseFloat(input3);
var sum = sum1(value1 , value3);
document.writeln("<h1> First number: " + value1 + "</h1>");
document.writeln("<h1> Second number: " + value3 + "</h1>");
document.writeln("<h1> Sum: " + sum + "</h1>");
function sum1 (x,y)
{
return (x+y);
}
Also, as Adriani6 mentioned you don't need to parseFloat again inside sum1 as you assign a parsed float already to value1 and value3
Although a bit dirty, this works:
var amount = 58.02;
var total = '£' + (amount*1 + 177);
...gives the the expected answer of £217.73
Enclosing within brackets forces 'amount' to be a number. However...
var amount = 40.73;
var total = '£' + (amount*1 + 177.82);
gives a really silly answer of £218.54999999999998 (!)
[ Edited 26th January - following part in italics kept for reference...
This is only true if the (correct) decimal part of the answer is .55 or .65 Bug in Javascript???? (It's the same in Firefox and Chrome.)
So some more manipulation is required to be absolutely certain: multiplication, integerising and subsequent division by 100...
var amount = 40.73;
document.write('Total is: £' + parseInt(amount*100 + 17782) / 100);
.. gives the correct answer of 'Total is: £218.55' ]
Edit: Better solution found later uses toFixed() :-
var amount = 40.73;
var total = 'Total is: £' + (amount* + 177.82).toFixed(2);
.. also gives the correct answer of 'Total is: £218.55'
Soooooo -
1) You need to enclose the numbers you want to add within brackets if the sum will be part of a string;
2) Multiplying each 'number' by one forces the result to be a number - so (input1*1 + input2*1) is forced to be the arithmetic sum. This is necessary in the original questioner's script, but multiplying by one isn't needed in my example;
3) To ensure you don't get a silly answer, append .toFixed(n) to the bracketed expression - where n is the number of decimal places.
Utterly tedious (still)....
(and) Much better to use PHP if you can!
The error you're seeing is here:
sum(value1 + value3)
Your sum function expects the arguments separately and will internally perform the addition, but you're adding them in-line before sending them to the function. Since only one value is sent to sum(), its second argument is undefined and therefore "not a number". Simply separate the values:
sum(value1, value3)
The other error that you may not have noticed yet is here:
parseFloat(input1 + input2)
If you enter 1 and 2 for example, the result of this will be 12. This is because you're "adding" (concatenating) the strings before converting them to a numeric value. Convert them first, then add them. Something like this:
var value1 = parseFloat(input1) + parseFloat(input2);
Aside from that the code can probably be cleaned up a bit more, such as not needing all of the parsing you're doing. (Once something is parsed to a numeric value, it doesn't need to be parsed to a numeric value again.) You'd also do well to look into setting values to elements on the page instead of using things like document.writeln(), but that could be a lesson for another day.
Because in Javascript, the + operator is overloaded, i.e., has multiple meanings depending on the arguments you give it. The + means concatenation for strings and addition for "numbers" (for different types of numbers).
You can use an add function that takes and ads as many parameters as you need:
function add() {
// Create an array from the functions arguments object
// then sum the array members using reduce
var sum = Array.from(arguments).reduce(function(a, b) {
return a + b;
});
console.log(sum);
}
// You can now add as many numbers as you like
// just by passing them to the function
add(2, 5);
add(2, 3, 5);

using the digits of a number as an array

var number = 342345820139586830203845861938475676
var output = []
var sum = 0;
while (number) {
output.push(number % 10);
number = Math.floor(number/10);
}
output = output.reverse();
function addTerms () {
for (i = 0; i < output.length; i=i+2) {
var term = Math.pow(output[i], output[i+1]);
sum += term;
}
return sum;
}
document.write(output);
document.write("<br>");
document.write(addTerms());
I am trying to take that large number and split it into its digits. Then, find the sum of the the first digit raised to the power of the 2nd, 3rd digit raiseed to the 4th, 5th raised to the 6th and so on. for some reason, my array is returning weird digits, causing my sum to be off. the correct answer is 2517052. Thanks
You're running into precision issues within JavaScript. Just evaluate the current value of number before you start doing anything, and the results may surprise you:
>>> var number = 342345820139586830203845861938475676; number;
3.423458201395868e+35
See also: What is JavaScript's highest integer value that a Number can go to without losing precision?
To resolve your issue, I'd store your input number as an array (or maybe even a string), then pull the digits off of that.
This will solve your calculation with the expected result of 2517052:
var number = "342345820139586830203845861938475676";
var sum = 0;
for(var i=0; i<number.length; i=i+2){
sum += Math.pow(number.charAt(i), number.charAt(i+1));
}
sum;
JavaScript stores numbers in floating point format (commonly double). double can store precisely only 15 digits.
You can use string to store this large number.
As mentioned, this is a problem with numeric precision. It applies to all programming languages that use native numeric formats. Your problem works fine if you use a string instead
var number = '342345820139586830203845861938475676'
var digits = number.split('')
var total = 0
while (digits.length > 1) {
var [n, power] = digits.splice(0, 2)
total += Math.pow(n, power)
}
(the result is 2517052, byt the way!)
Cast the number as a string and then iterate through it doing your math.
var number = "342345820139586830203845861938475676";//number definition
var X = 0;//some iterator
var numberAtX = 0 + number.charAt(X);//number access
The greatest integer supported by Javascript is 9007199254740992. So that only your output is weird.
For Reference go through the link http://ecma262-5.com/ELS5_HTML.htm#Section_8.5
[edit] adjusted the answer based on Borodins comment.
Mmm, I think the result should be 2517052. I'd say this does the same:
var numbers = '342345820139586830203845861938475676'.split('')
,num = numbers.splice(0,2)
,result = Math.pow(num[0],num[1]);
while ( (num = numbers.splice(0,2)) && num.length ){
result += Math.pow(num[0],num[1]);
}
console.log(result); //=> 2517052
The array methods map and reduce are supported in modern browsers,
and could be worth defining in older browsers. This is a good opportunity,
if you haven't used them before.
If you are going to make an array of a string anyway,
match pairs of digits instead of splitting to single digits.
This example takes numbers or strings.
function sumPower(s){
return String(s).match(/\d{2}/g).map(function(itm){
return Math.pow(itm.charAt(0), itm.charAt(1));
}).reduce(function(a, b){
return a+b;
});
}
sumPower('342345820139586830203845861938475676');
alert(sumPower(s))
/*
returned value:(Number)
2517052
*/

Simple math in jquery

I am reading a select form value and multiplying it by 50 in jquery. I need to add a value of 1 to the qty that is returned by the select menu every time before multiplying by 50. How would I do that? The offending code looks like this.
$('#selectform').val() *50);
If I use
$('#selectform').val() +1 *50);
The result is not correct.
Parentheses should be used.
($('#selectform').val()*1 + 1) *50;
Your current expression is interpreted as:
var something = $('#selectform').val();
var another = 1 * 50;
var result = something + another
The *1 after .val() is used to convert the string value to a number. If it's omitted, the expression will be interpreted as:
var something = $('#selectform').val() + "1"; //String operation
var result = something * 50; // something is converted to a number, and
// multiplied by 50
Correct parentheses and use parseInt function -
(parseInt($('#selectform').val(),10) +1) *50;
The data from $('#selectform').val() is probably being treated as a string.
Use parseInt($('#selectform').val()) to convert it to an int before the multiply.
You should have a look at the operator precedence in JavaScript.
You need to force the addition to happen before the multiplication with parentheses:
bar myVal = ($("#selectform").val() + 1) * 50;

How do I add an integer value with javascript (jquery) to a value that's returning a string?

I have a simple html block like:
<span id="replies">8</span>
Using jquery I'm trying to add a 1 to the value (8).
var currentValue = $("#replies").text();
var newValue = currentValue + 1;
$("replies").text(newValue);
What's happening is it is appearing like:
81
then
811
not 9, which would be the correct answer. What am I doing wrong?
parseInt() will force it to be type integer, or will be NaN (not a number) if it cannot perform the conversion.
var currentValue = parseInt($("#replies").text(),10);
The second paramter (radix) makes sure it is parsed as a decimal number.
Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used
var currentValue = parseInt($("#replies").text(),10);
The integer is being converted into a string rather than vice-versa. You want:
var newValue = parseInt(currentValue) + 1
parseInt didn't work for me in IE. So I simply used + on the variable you want as an integer.
var currentValue = $("#replies").text();
var newValue = +currentValue + 1;
$("replies").text(newValue);
In regards to the octal misinterpretation of .js - I just used this...
parseInt(parseFloat(nv))
and after testing with leading zeros, came back everytime with the correct representation.
hope this helps.
to increment by one you can do something like
var newValue = currentValue ++;
Simply, add a plus sign before the text value
var newValue = +currentValue + 1;
Your code should like this:
<span id="replies">8</span>
var currentValue = $("#replies").text();
var newValue = parseInt(parseFloat(currentValue)) + 1;
$("replies").text(newValue);
Hacks N Tricks
var month = new Date().getMonth();
var newmon = month + 1;
$('#month').html((newmon < 10 ? '0' : '') + newmon );
I simply fixed your month issue, getMonth array start from 0 to 11.
You can multiply the variable by 1 to force JavaScript to convert the variable to a number for you and then add it to your other value. This works because multiplication isn't overloaded as addition is. Some may say that this is less clear than parseInt, but it is a way to do it and it hasn't been mentioned yet.
You can use parseInt() method to convert string to integer in javascript
You just change the code like this
$("replies").text(parseInt($("replies").text(),10) + 1);

Categories