Rounding a Number variable in javascript [duplicate] - javascript

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

Related

Calculating currency [duplicate]

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.

Generate a big random float jquery/JavaScript [duplicate]

This question already has answers here:
How to deal with big numbers in javascript [duplicate]
(3 answers)
Closed 8 years ago.
I need to generate a 12 digit and 13 decimals float value like this:
123438767411.238792938
How can I do that in Javascript/Jquery? Is it possible to generate this code using JavaScript?
I was trying like this:
v1 = Math.floor((Math.random()*10000000000)+1);
v2 = Math.floor((Math.random()*100000000)+1);
v = v1.toString() + "." + v2.toString();
But this is not working!
(assuming you mean in the form of a string, not as a number, because IEEE 754 can't have that many significant digits)
must the integer part be 12 digits or can it be 1 or 123? If it can be 12 digits or shorter, then it can be
(Math.floor (Math.random() * Math.pow(10,12))
+ (Math.floor (Math.random() * Math.pow(10,13))
/ Math.pow(10,13)).toString().substring(1))
note that the above could have an issue when the decimal part turns out to be 0, although the chance is really small. (then the .0 part is gone, although we can use a conditional to add it when it is so). Or we can treat the decimal part 123 not as .0000000000123 but as .123 and use:
(Math.floor (Math.random() * Math.pow(10,12))
+ "." + Math.floor (Math.random() * Math.pow(10,13)))
But it depends whether we care about 123 becoming .123 and 1230 also becoming .1230 because if we do care about it, we can say .123 is the same as .1230.
Also, if we want to have the form such as 000042987017.0790946977900 as well, so that it is always 12 digit integer and 13 digit decimal, then either we can do zero padding or use something like this:
sample: http://jsfiddle.net/jL4t4/1/
var i, s = "";
for (i = 0; i < 26; i++) {
s += (i === 12) ? "." : Math.floor(Math.random() * 10);
}

Rounding a number up [duplicate]

This question already has answers here:
Rounding numbers to 2 digits after comma
(10 answers)
Closed 9 years ago.
I want to round the up my total til two decimal places.
I have this:
var updateTotal = function () {
var people = parseInt($('#people').val());
var bill = parseInt($('#bill').val());
var tip = parseInt($('#tip').val());
var billTip = bill + tip;
$('#total').text(billTip / people);
and i've also found this snippet to help round up but i cant seem to get my head around how to implement it.
var rounded = Math.round((10 / 3) * 100) / 100;
Thanks
It's already implemented for you. Substitue (10 / 3) for your own variables. All it's doing is shifting the decimal place two places to the right (by multiplying by 100), rounding, then shifting it two left (by dividing by 100).
var rounded = Math.round((billTip / people) * 100) / 100;
You can also use .toFixed
$('#total').text((billTip / people).toFixed(2));
I would use parseFloat on both your numbers, or else it will round to 00:
$('#total').text(parseFloat(billTip / people).toFixed(2));
You can use ceil function Math.ceil(billTip)
and for refernce you can also visit below link
http://www.w3schools.com/jsref/jsref_ceil.asp

Multiplication results in unusual decimal places [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is JavaScript’s Floating-Point Math Broken?
I have a strange mathematical problem during a multiplication in javascript.
$(parent).find('#id_deals-' + i + '-quantity').val()
result -> 10
$(parent).find('#id_deals-' + i + '-price').val()
result -> 3.99
Both above mulltiplied like this:
$(parent).find('#id_deals-' + i + '-price').val() * $(parent).find('#id_deals-' + i + '-quantity').val()
result --> 39.900000000000006
Why is this happening? and what can I do to limit the decimal places to 2 digits only?
Is it maybe because 10 has to be 10.0 ? But how do I convert my value to this format automatically before the actual multiplication?
Update:
According to syazdani's answer, I have tried to implement bigdecimal as suggested:
It is not well documented, but I got it working like this:
function run(opts) {
var bd = {"BigDecimal":BigDecimal, "BigInteger":BigInteger, "RoundingMode":RoundingMode};
var result;
var ops = {'*': "multiply", '/': "divide", '+': "add", '-': "subtract"};
var a = new bd.BigDecimal("" + opts.a);
var b = new bd.BigDecimal("" + opts.b);
var op = ops[opts.op];
if (op == "divide") {
return a.divide(b, 300, bd.RoundingMode.HALF_UP());
} else {
return a[op].call(a, b);
}
}
function multiply(a, b){
return run({"a":a,"b":b,"op":"*"});
}
If you are working with currency (as it seems that you are given the "price" id), you may be better served by using a so called Big Number library (such as this one: https://github.com/iriscouch/bigdecimal.js) for your math to control the math (round up vs round down, etc.). It takes a bit more work to get everything right, but it is worthwhile to avoid the Office Space math scenario.
All javascript number are IEEE-754 double precision floating points numbers. That means that they suffer from round-off errors and imprecision.
All numbers in javascript are floating point numbers, based on IEEE754.
If you want to format one as a string with a fixed number of digits after the dot, use
var formattedNumber = v.toFixed(2); // this makes a string

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

Categories