parsing decimals into a span
<input value="123" />
<span></span>
$('input').change(function (){
var val = $(this).val().toFixed(2);
$('span').text(val);
});
I have tried the code above but can't seem to get the decimal on the text()
is just shows as 123. This is my first time exp开发者_如何学Pythonerimentind with toFixed()
just in case toFixed()
is a js
native method not a jquery
toFixed
is a method that you would call on a number, not on a string. You need to parse the string to a number:
var val = parseFloat($(this).val(), 10).toFixed(2);
Live demo here: http://jsfiddle.net/QrW5C/
Look at the error console. You should see something like:
TypeError: Object 123 has no method 'toFixed'
Strings don't have the toFixed()
method. Only numbers have. Convert the value to a number first (e.g. by prepending +
):
var val = (+$(this).val()).toFixed(2);
DEMO
You need to parse it:
var NumericValue = parseFloat($(this).val())
var val = NumericValue .toFixed(2);
info here: http://www.bennadel.com/blog/1013-Javascript-Number-toFixed-Method.htm
also:
<span></spam> (?)
精彩评论