1

I have a simple conversion form from kg to lbs.

html

<input type="text" id="kg" name="kg">
<input type="text" id="lbs" name="lbs">

I have it setup so that the lbs box updates while you type in the kg box with this code.

jQuery

$("#kg").keyup(function(){
    $('#lbs').val($('#kg').val()*2.20462);
});

How do I get the lbs value to round to 2 decimals places? I am sure it is something fairly simple but all the examples I found online are for if the number is stored in a variable.

gdoron
  • 147,333
  • 58
  • 291
  • 367
user1738750
  • 205
  • 4
  • 15

3 Answers3

3

Use toFixed

var string = yourNumber.toFixed(2);
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • @ZoltanToth To be fair... there is probably a jQuery plugin for that (I know I made a js lib for more advanced number formatting) – Denys Séguret Nov 19 '12 at 16:20
2

use toFixed:

$('#lbs').val(($('#kg').val()*2.20462).toFixed(2));

number.toFixed( [digits] )

Parameter

digits The number of digits to appear after the decimal point; this may be a value between 0 and 20, inclusive, and implementations may optionally support a larger range of values. If this argument is omitted, it is treated as 0.

Returns

A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If number is greater than 1e+21, this method simply calls Number.toString() and returns a string in exponential notation.

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • Wow I was SO close! I was trying this `$('#lbs').val($('#kg').val()*2.20462).toFixed(2);` Thank you so much! I will accept your awnser when it lets me in 10 minutes. – user1738750 Nov 19 '12 at 16:21
  • @user1738750, yes, your's has an error with the braces, but you were close indeed. :) – gdoron Nov 19 '12 at 16:23
1

also this

(10.8).toFixed(2); // 10.80

var num = 2.4;
alert(num.toFixed(2)); // 2.40

Formatting a number with exactly two decimals in JavaScript

Community
  • 1
  • 1
Andrei Cristian Prodan
  • 1,114
  • 4
  • 17
  • 34