1

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/

Jatin
  • 3,065
  • 6
  • 28
  • 42
AlwaysLearning
  • 197
  • 3
  • 5
  • 13

3 Answers3

3
$("#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.

alex
  • 479,566
  • 201
  • 878
  • 984
1
  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);
Sahil Saini
  • 250
  • 5
  • 11
0

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