I understand that JS math is not perfect. but how can i format this to get the correct answer as I have a cart item which costs .60 cents and they can change the quantity?
var a=3*.6;
document.write(a);
writes 1.7999999999999998
Obviously I want to write 1.8. any ideas how to accomplish this?
Use toFixed to round it back:
var a = 3*.6;
document.write(a.toFixed(2));
If you need it as a number, add a + sign before it:
var a = 3*.6;
console.log(+a.toFixed(2)); // Logs: 1.8, instead of "1.80"
var a=3*.6;
a = Math.round(a*10)/10;
document.write(a);
Since you want to round to the 10ths place, you need to multiply the number by 10, round the result of that multiplication to the nearest whole number, and then divide the result by 10.
It's not sexy, but ya gotta do whatchya gotta do.
var a=(3*(.6*100))/100;
document.write(a);
Example: http://jsfiddle.net/aJTJq/
multiply .6 by 100 to get the 60 cents
multiply that by 3
divide it by 100 to return it as a dollar figure
Write the .6 as a fraction: a=3*6/10 and you get 1.8
As a more general rule, you could try rounding to the nearest millionth with
Math.round(result*1000000)/100000 and seeing what that gets you.
What you want to do is have some type of rounding function.
Try this:
Rounding Function
<script language="javascript" type="text/javascript">
function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places
var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
document.roundform.numberfield.value = parseFloat(newnumber); // Output the result to the form field (change for your purposes)
}
</script>
And then something like this to call the function
<form name="roundform">
<input type="text" name="numberfield" value="">
<input type="button" value="Round" onClick="roundNumber(numberfield.value, 2);">
</form>
This example just takes a number in the text field and ensures that it is rounded to two decimal places.
This was taken from http://www.mediacollege.com/internet/javascript/number/round.html
There are more examples on this link as well. Hopefully this helps.
Cheers
Related
I have a number that increases every second by addition. The problem is that it contains way too many decimals. An example of an output which I do not want would be something like 1.5999999999999999 or 1.600000000001. I have tried using the toFixed method, passing in 2 as it's value, and I am still getting the issue. I have also tried using the Math.round(number * 100) / 100 and am still getting uggly decimals.
How can I get an output that only contains a specified number of decimal points? I want to be able to choose how the number rounds. The function to round should be something like this:
function round(numberToRound, afterDecimals){
//Rounding code which takes into the account the number of decimal values I wish to display should go here
}
Thank you.
I am so sorry, I didn't call the function in the right place. The function works as expected, I just wasn't updating the innerHTML correctly.
Again, I am sorry for overlooking this.
I have a JavaScript calculator which uses the Math.cbrt() function. When I calculate the cube root of 125 it returns 4.999999999999999. I understand that I could use Math.round() to round any answers that this function returns to integer values, but I do not want to do that exactly. Is there a way to use this if and only if the result of calculation is some number followed by a string of 9s (or something similar like 4.99999998 perhaps) after the decimal?
What you are dealing with is the frustration of floating point numbers in computing. See the Floating Point Guide for more information on this critical topic.
The short version:
Certain non-integer values cannot be represented accurately by computers, so they store a value that is "near enough". Just try evaluating 3.3 / 3 in your favourite REPL.
Say what?!
Computers are supposed to be perfect at this numbers/math thing, right? Can I trust any answer they give me?
Yes, for integers, they are pretty much perfect. But for non-integer calculations, you should assume that answers won't be exact, and account for these floating point errors.
The solution in Javascript
In newer versions of Javascript, you have a defined constant Number.EPSILON, which is the smallest difference between the actual number and the approximation that it can actually store.
Using this, you can multiply that constant by the result you get and add it to the result and you should get the exact value you require.
function cbrt(n) {
return Math.cbrt(n) + (Number.EPSILON * Math.cbrt(n));
}
Alternatively, you can use the rounding behaviour of the .toFixed() method on numbers together with the parseFloat() function if you only care about numbers up to a certain number of decimal places (less than 20).
function num(n, prec) {
if (prec === void 0) prec = 8; // default to 8 decimal places
return parseFloat(n.toFixed(prec));
}
var threshold = 0.999; // set to whatever you want
var fraction = result % 1;
if (fraction >= threshold) {
result = Math.round(result);
}
I know this maybe very simple and common but I want to know about this calculation:
Example: I have a decimal number 4.716981132075472, but I only need the 4 number, is there any calculation able to do this?
Try round off:
var result = 4.716981132075472 << 0;
alert(result);
OR
var result = Math.floor(4.716981132075472);
alert(result);
You are looking for Math.floor() docs here
Try Math.floor( 4.716981132075472);. This rounds the number down to the nearest integer, thus solving your problem.
My employer wishes for a textbox to convert feet to metres to one decimal place, however, I am unfamiliar with Javascript and only know the bare basics for HTML purposes. My current code converts it correctly, but it is not to one decimal place.. Any suggestions?
Code:
<script type="text/javascript">
<!--
function validate() {
var ft = document.getElementById('LengthFt');
var res=0.3048*ft.value;
var mtrs = document.getElementById('LengthMtrs');
mtrs.value = res;
}
//-->
</script>
It looks like you've done the conversion. After that, all you need to do is format the number properly.
The toFixed method can be used to format to a fixed number of decimal places.
Replacing
mtrs.value = res;
with
mtrs.value = res.toFixed(1);
should leave the right number in the LengthMtrs input accurate to the closest decimeter.
I am trying to do a select box with 4 options
00,15,30,45
I want to take the current time and round it to 15 min increments, and have the value change.
I have
current_min = start_date.getMinutes();
$('#event-hour').val(current_min);
I played with this roundedMinutes=(15*Math.floor(enteredMinutes/15)) but i couldn't get it to work right.
Use Math.round instead of Math.floor and everything should be ok-- other than that, your equation for rounding to the nearest n is correct.
currentTimeRounded = (15*Math.round(date.getMinutes()/15));
js> (15*Math.round(date.getMinutes()/15));
15
Works just fine for me.