# How can I Round up numbers in this conversion table

Printable View

• 10-07-2012, 02:11 PM
dobbies
How can I Round up numbers in this conversion table
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
}

//-->
• 10-07-2012, 03:13 PM
jmrker
Try...
Code:

`document.convert.ltr.value = (m / ltrValue).toFixed(2);`
• 10-08-2012, 12:14 PM
dobbies
Quote:

Originally Posted by jmrker
Try...
Code:

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

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

Cheers!
• 10-08-2012, 12:27 PM
shyagrawal
you can also use
DecimalFormat df = new DecimalFormat("0.00");
• 10-08-2012, 03:39 PM
Philip M
Quote:

Originally Posted by shyagrawal
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

Code:

```<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>```