Val
Val

Reputation: 17532

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 experimentind with toFixed()

just in case toFixed() is a js native method not a jquery

Upvotes: 4

Views: 4423

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039288

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/

Upvotes: 12

Luke Duddridge
Luke Duddridge

Reputation: 4347

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> (?)

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816900

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

Upvotes: 0

Related Questions