Calculating currency [duplicate] - javascript

This question already has answers here:
Problems with JavaScript "parseInt()" decimal string
(5 answers)
Closed 4 years ago.
im trying to calculate currency but when i try it calculates only first number (1.25$+1.25$ returns 2$) this is the code that i made <-- done
var table = document.getElementById("table"), sumVal = 0;
for (var i = 1; i < table.rows.length; i++)
{
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
document.getElementById("val").innerHTML = +sumVal + "€";
console.log(sumVal);
what should i add or edit so i can calculate entire value of that row and return 2 dollars and 50 cents

replace parseInt with parseFloat

I guess parseInt will translate your 1.25 value to 1, try parseFloat

As others have said, use parseFloat instead of parseInt, but you should also multiply those numbers by 100 and then divide your answer by 100 as you don't want to run into floating point errors.

Related

Javascript Math.ceil and Math.pow returning wrong answer [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
Does anyone know why the exponent and round up functions aren't giving me the correct answers? I've gone through a load of debugging and I can't figure out what I'm doing that's making it's value abnormally large (like 25 orders larger)
function CAPEX(){
var initial = document.getElementById("CAPEX").value;
var lifespan = document.getElementById("life").value;
var interest = document.getElementById("IR").value;
var capitalrepayment = initial/lifespan;
var i;
var cap=0;
var expense =0;
for (i=0; i<lifespan;i++){
expense = capitalrepayment + (initial*interest);
cap = cap + expense;
initial = initial - capitalrepayment;
}
denominator = Math.pow((1+interest), lifespan);
console.log(denominator);
return cap;
}
I have a similar sort of issue here too where Math.ceil is returning a completely different answer too.
if(selected_scenario == "Divers"){
var totalTechnicians = numberNeeded * 3;
var supervisors = totalTechnicians/3;
var othertechnicians = totalTechnicians-supervisors;
var boats= Math.ceil((totalTechnicians+numberNeeded)/12);
divertotal = (numberNeeded*580)+(supervisors*516)+(othertechnicians*276)+(boats*2345)+9230+(boats*20);
}
For reference interest is 0.02, lifespan is 25, numberNeeded is 23. I'm reading these values in directly from a form number input.
The denominator should be 1.64 and boats should be 8.
The values that you are getting from the DOM are strings. You need to convert them to numbers before you can apply any mathematical operations to them. Try using parseInt() or parseFloat()

Rounding a Number variable in javascript [duplicate]

This question already has answers here:
Formatting a number with exactly two decimals in JavaScript
(32 answers)
Closed 6 years ago.
I have this code:
function sellByte() {
if (player.bytes >= 1) {
player.bytes = player.bytes - 1;
player.money = player.money + 0.10;
document.getElementById("bytes").innerHTML = "Bytes: " + player.bytes;
document.getElementById("money").innerHTML = "$" + player.money;
}
}
And whenever I sell a Byte my money value ends up looking like $10.00000003 or something along those lines, how would I go about rounding the money value UP every time this function is run?
Working with float numbers in JS is very tricky. My suggestion is to operate only with smaller units (cents instead of dollars) and then you will only deal with integers and will not have similar issues.
Use Math.round(player.money* 100) / 100 for 2 decimal rounding.
Use any of the following code
Math.round(num * 100) / 100
using fixed Method
var numb = 123.23454;
numb = numb.toFixed(2);
or you can refer following link for more help
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

how to get 1.450 = 1.5 in javascript? (round to 1 decimal place) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you round to 1 decimal place in Javascript?
My Value is 1.450 and I have to round it to 1 decimal place.
I want 1.450 = 1.5 in Javascript can any body fix this please.
You need this:
var mynum = 1.450,
rounded = Math.round(mynum * 10) / 10;
suppose you have
var original=28.453;
Then
var result=Math.round(original*10)/10 //returns 28.5
From http://www.javascriptkit.com/javatutors/round.shtml
You can also see How do you round to 1 decimal place in Javascript?
Given your fiddle, the simplest change would be:
result = sub.toFixed(1) + "M";
to:
result = Math.ceil(sub.toFixed(1)) + "M";
If you use Math.round then you will get 1 for 1.01, and not 1.0.
If you use toFixed you run into rounding issues.
If you want the best of both worlds combine the two:
(Math.round(1.01 * 10) / 10).toFixed(1)
You might want to create a function for this:
function roundedToFixed(_float, _digits){
var rounder = Math.pow(10, _digits);
return (Math.round(_float * rounder) / rounder).toFixed(_digits);
}

Input field values not adding up correctly [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is JavaScript's Math broken?
I'm attempting to add up three input fields, each containing a value of 33.3 which should total 99.9, however they are totaling to 99.89999999999999
Could someone explain how this is happening. Below is my code. Thanks in advance.
$("#modify-funding input.percentCalc").sumValues()
$.fn.sumValues = function () {
var sum = 0;
this.each(function () {
sum += $(this).fieldVal();
});
return sum;
};
$.fn.fieldVal = function () {
var val;
if ($(this).is(':input')) {
val = $(this).val();
alert("val " + val);
} else {
val = $(this).text();
}
return parseFloat(('0' + val).replace(/[^0-9-\.]/g, ''), 10);
};
Welcome to the wonderful world of floating point numbers. Floating points are aproximations of the number you want to represent. Thus when you save a number as 33.3 it is around but not exactly 33.3 this error adds up after multiple operations. The best way to compare floats is to not test for equality but to test weather they are in a range.
Instead of
if(x == 99.9)
try
if(Math.abs(99.9 - x) < .1)
If you just want the string representation. You could try handing the floating point number as an integer. i.e. 33.3 equals 333 then when you are turning it back into a string you add the decimal back in where appropriate. This would be the best solution for your problem.

Multiply numbers with more than 4 decimal points [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
round number in JavaScript to N decimal places
This may be easy for you guys,
My question is:
How can I control a decimal places in a floating point value.
Ex.: My result is returning 0.365999999999999; but I need to show just 4 decimal numbers.
Check the demo: Demo (I accept any others ways to calculate that)
Thanks!
You can use .toFixed
var number = 0.365999999999999;
var rounded = number.toFixed(4); // 0.3660
try this:
$("#test").keyup(function(){
var number = parseFloat($("#number").text());
var current = parseFloat($(this).val());
var total = number*current;
$("#result").val(total.toFixed(4));
});
$("#result").val(total.toFixed(4));
Javascript has a nice round function, but it only does integers so you have to multiply it by 10000 then divide the rounded result by 10000
http://www.javascriptkit.com/javatutors/round.shtml
The toFixed function always rounds up, but round will probably do what you want.
For proper rounding:
function roundNumber(number, digits) {
var multiple = Math.pow(10, digits);
var rndedNum = Math.round(number * multiple) / multiple;
return rndedNum;
}
For rounding up:
number.toFixed(4);
$("#test").keyup(function(){
var number = $("#number").text();
var current = $(this).val();
var total = parseFloat(number*current).toFixed(2);
$("#result").val(total);
});
Cast the variable to a float and then use the toFixed() method
If you follow the link below you can import the number_format php function to javascript. The function has been helping me for years now.
Here is the function signature :
function number_format (number, decimals, dec_point, thousands_sep)
http://phpjs.org/functions/number_format:481

Categories