-1

I am new to making websites. I am making one to convert grams of sugar into no of teaspoons. I am not able to understand how to limit the decimal points in the output.

<script type="text/javascript">

function calcTS() {
var g=document.getElementById('wt').value;
var ts=document.getElementById('Tspoon').value;

document.getElementById('Tspoon').value = g/4.2;
}   

function calcG() {
var g=document.getElementById('wt').value;
var ts=document.getElementById('Tspoon').value;

document.getElementById('wt').value= ts*4.20;
}

This is the output I am getting: 1 gram of sugar = 0.23809523809523808 teaspoons.

The output that I want: 1 gram of sugar = 0.2 teaspoons.

2 Answers2

4

You can use toFixed method to limit the decimals.

var num = 5.56789;
var n = num.toFixed(2);
console.log(n);
Jaydeep
  • 1,686
  • 1
  • 16
  • 29
1

Use toFixed and the parameter of it is how deep the result after the point.

document.getElementById('wt').value= (ts*4.20).toFixed(1);
Ziv Ben-Or
  • 1,149
  • 6
  • 15