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.
Related
Trying to do a simple JavaScript calculation
var money = $("#money").val();
var percentRate = "{{ $money->percent }}"/100;
var incomeMoney = money * percentRate;
If the $amount->percent is a whole number it will give a correct figure but if I use a decimal point it won't.
Eg if I assign 23 to $money->percent it will give me the correct figure but if I assign decimal like 23.5 it will give a wrong figure.
I believe the system is rounding the percentRate to 0.23 instead of 0.235. How do I get around this, Please?
Full code -
...
Good day,
I am still learning JS and HTML and I noticed something quite interesting for me
I am using Google Geocoding scripts and created an on click event on the map to retrieve the GPS co-ordinates,
function onClickCallback(event){
var str = event.latLng.toString().slice(1,-1).split(',', 2);
var lat1 = parseFloat(str[0]).toFixed(5);
var lng1 = parseFloat(str[1]).toFixed(5);
var latlng1 = new google.maps.LatLng(lat1,lng1).toString().slice(1,-1);
document.getElementById('latlng').value = latlng1;
this works perfectly for my needs however for some odd reason the second part "lng1" does not round down as expected and as an example the below is the result
-25.3341, 27.64984000000004 or -25.34403, 27.97393999999997
as the first part 'lat1' works fine what is the reason or cause for the second part 'lng1' not rounding and only displaying the first 5 decimals and how can I fix it
The problem is most likely a combination of type conversion and javascript's built in floating point number representation.
When you call toFixed() your number is actually converted to a string with the desired number of decimals. google.maps.LatLng() expects two numbers but, since you're not getting any errors, is also fine receiving string representations of numbers instead.
Internally, I assume google.maps.LatLng() converts the lat1 and lng1 arguments to numbers again. Since the way javascript represents numbers often results in small rounding errors, the toString() gets lng1, which is now a number again and likely slightly different than what toFixed() originally returned, and converts it back to a string.
If you want to be able to output nice numbers, you could postpone the toFixed() calls until the end:
...
var lat1Formatted = parseFloat(latlng1.split(', ')[0]).toFixed(5);
var lng1Formatted = parseFloat(latlng1.split(', ')[1]).toFixed(5);
document.getElementById('latlng').value = lat1Formatted + ', ' + lng1Formatted;
I have a script where i can put in a number in one text box and it will calculate the equivalent in the other textboxes.
$("input[type=text]").keyup(function () {
var number = parseFloat($(this).val());
var inc = parseFloat($(this).attr("inc"));
var newValue = number / inc;
$("input[type=text]").each(function () {
if(isNaN(newValue * parseFloat($(this).attr("inc"))))
$(this).val(0);
else
$(this).val(newValue * parseFloat($(this).attr("inc")));
});
});
Can check : JSFiddle Here
At the moment it doesn't allow for decimal numbers. But i really need it to. And i don't know how to allow a decimal.
Also i need the box's to have a limit of 2 numbers ofter the decimal point.
TL;DR: Skip to the actual code if you just want the fix. The following paragraphs explains why it is happening.
The reason the decimal numbers aren't working is every single time the text box get edited by a single character, all numbers in all text boxes are converted to a float. If you type 1 into one of the boxes, the value gets passed to parseFloat and gets converted to 1 (the same value). If you then press the 3 character, the text box says 13, which gets passed to parseFloat and returns the same value, 13.
However, if you start typing 13., that gets passed to parseFloat; JavaScript realizes the period is unnecessary*, and places the value 13 in the text box. No matter how fast you type, JavaScript will keep wanting to trim off that "unnecessary" period before you can add extra digits to the end.
You can solve this by only running parseFloat function (or changing the value in any way) on the text fields you are not currently typing in. I have emphasized the two lines in which "the magic happens":
$("input[type=text]").keyup(function () {
var number = parseFloat($(this).val());
var inc = parseFloat($(this).attr("inc"));
var newValue = number / inc;
var current = this; // <---- "current" is the text field that is currently being edited
$("input[type=text]").each(function () {
if(this != current) { // <--------------
if (isNaN(newValue * parseFloat($(this).attr("inc"))))
$(this).val(0);
else
$(this).val(newValue * parseFloat($(this).attr("inc")));
}
});
});
And a JS Fiddle of the code so you can test it: http://jsfiddle.net/RX2sL/27/
* Technically the period gets trimmed off due to the String -> Float -> String conversion, but it's easier to think of the period as being "unnecessary".
I am trying to make a javascript program that calculates the area of a trapezoid. So far below is my js code:
var lol=prompt("Please enter which 2d polygon you would like this awesome calculator to calculate.")
if(lol==="trapezoid"){
var tr1=prompt("Enter the top base.")
var tr2=prompt("Enter the bottom base.")
var tr3=prompt("Now enter the height.")
confirm((tr1+tr2)*(tr3)/2)
}
But when I put 4,5,6 in my calculator, it spits out 135 instead of 27.
Why?
You can use parseInt to set the values as integers.
var lol=prompt("Please enter which 2d polygon you would like this awesome calculator to calculate.")
if(lol==="trapezoid"){
var tr1=Number(prompt("Enter the top base."))
var tr2=Number(prompt("Enter the bottom base."))
var tr3=Number(prompt("Now enter the height."))
confirm((tr1+tr2)*(tr3)/2)
}
Here's a JSFiddle with Benjamine's Number point
http://jsfiddle.net/cXWnk/
The values you are getting back from the prompt are strings and, as Ryan P says, "1" + "1" = "11".
What you need to do is cast the strings to integers before using their values in the calculation.
You can do this with the Number() function.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
So, your code might be:
confirm((Number(tr1) + Number(tr2)) *(Number(tr3))/2)
or, using the unary plus shorthand:
confirm((+tr1 + +tr2)*(+tr3)/2)
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