Reputation: 1397
Most important thing here is that I can NOT set a variable, needs to be on the fly:
Dealing with latitude. Let's call it lat. Let's say in this case lat is 123.4567
lat.toFixed(2).parseFloat();
TypeError: Object 123.35 has no method 'parseFloat'
Best way to go about this?
Upvotes: 0
Views: 1260
Reputation: 23492
toFixed
is a method of Number
and returns a string. window.parseFloat
is a global function and not a method of String
, but if you really must, then you can make it a String
method, otherwise just use it as a function. You can even use the unary plus operator in this case.
(There is a great deal of discussion about augmenting native objects that I am not going to go into, you can do some research and make up your own mind.)
Javascript
if (!String.prototype.parseFloat) {
String.prototype.parseFloat = function () {
return parseFloat(this);
}
}
var lat = 123.456789;
console.log(parseFloat(lat.toFixed(2)));
console.log(lat.toFixed(2).parseFloat());
console.log(+lat.toFixed(2));
Output
123.46
123.46
123.46
On jsfiddle
Upvotes: 5