...

View Full Version : How can I Round up numbers in this conversion table



dobbies
10-07-2012, 02:11 PM
I am using this code to convert liquid volume but it converts too many decimal places. Could someone show me how to reduce the conversion to 1 or 2 decimal places?

Many thanks

// JavaScript Document
<!--

function nofocus()
{
document.convert.InUnit.focus()
}
var mlValue = 1
var ltrValue = 1000
var fozValue = 28.4
var cupValue = 236
var ptValue = 568.261

function toCM()
{
var i = document.convert.unit.selectedIndex
var thisUnit = document.convert.unit.options[i].value
if (thisUnit == "ML")
{
document.convert.ml.value = document.convert.InUnit.value
}

else if(thisUnit == "LTR")
{
document.convert.ml.value = document.convert.InUnit.value * ltrValue
}

else if(thisUnit == "FOZ" )
{
document.convert.ml.value = document.convert.InUnit.value * fozValue
}

else if(thisUnit == "CUP" )
{
document.convert.ml.value = document.convert.InUnit.value * cupValue
}

else if(thisUnit == "PT" )

{
document.convert.ml.value = document.convert.InUnit.value * ptValue
}


toAll()
}
function toAll()
{
var m = document.convert.ml.value
document.convert.ltr.value = m / ltrValue
document.convert.foz.value = m / fozValue
document.convert.pt.value = m / ptValue
document.convert.cup.value = m / cupValue
}

//-->

jmrker
10-07-2012, 03:13 PM
Try...


document.convert.ltr.value = (m / ltrValue).toFixed(2);

dobbies
10-08-2012, 12:14 PM
Try...


document.convert.ltr.value = (m / ltrValue).toFixed(2);


The above worked perfectly, many thanks for your time and help.

Cheers!

shyagrawal
10-08-2012, 12:27 PM
you can also use
DecimalFormat df = new DecimalFormat("0.00");

Philip M
10-08-2012, 03:39 PM
you can also use
DecimalFormat df = new DecimalFormat("0.00");

No. that is Java, not Javascript.

As well as toFixed() which results in a string value you can use


<script type = "text/javascript">

roundNumber = function(num, dec) {
return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
}

alert (roundNumber(123.45678,2));

</script>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum