Question

I have the following code that works with the exception of limiting the #result2 to 3 digits

current #result2: input 1 and you get 0.010416666666666666

needed #result2: input 1 and get 0.01

I need to limit the result to 0.00 2 digits after so that it is not a long result.

This is going to be used to convert pixels to inches for designers as part of a pet project.

** What would be really great is if the result would actually convert to inches, example: input 1 and get back 1/8 but not sure if that can be done???

Here is the Html:

<label>Pixels</label>
<input class="calcd" id="calc3" type="text" />
<input class="calcd" id="calc4" type="hidden" value="96" />
<p>Inches</p><span id="result2"></span>

Here is the Jquery:

$(document).ready(function(){

    $(".calcd").keyup(function(){

        var val1 = parseInt($("#calc3").val());
        var val2 = parseInt($("#calc4").val());

        if ( ! isNaN(val1) && ! isNaN(val2))
        {
             $("#result2").text(val1 / val2).toFixed(3);
        }
    });

});

Thanks in advance!

Here is the JSFIDDLE: http://jsfiddle.net/4ZdJL/

Was it helpful?

Solution

$("#result2").text(val1 / val2).toFixed(3);

There's your problem. You want to call toFixed(3) on the value before you pass it to text().

$("#result2").text((val1 / val2).toFixed(3));

It may be useful to step through with a debugger at times like this, to see where expressions are evaluated and how it works.

OTHER TIPS

  1. Basically toFixed convert the number into string and apply only on String.
  2. Get the values in different variables and store the result in variable and apply toFixed.
var val1 = parseInt($("#calc3").val());
var val2 = parseInt($("#calc4").val());

var result = (val1 / val2).toFixed(3);

2.Store the value in textbox.

$("#result2").text(result); 

OR

 $("#result2").val(result);

2 digits as Int not work for fixed, if you use parseFloat().toFixed() works as a charm! and is cleaner if you ask me!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top