0

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?

Nubtacular
  • 1,367
  • 2
  • 18
  • 38
  • 3
    Well, you need to pass something to `parseFloat`, which is a function and not a method, so...`parseFloat(lat.toFixed(2));`. If you wanted to be able to use chaining, you could modify `String`'s prototype, like: `String.prototype.parseFloat = function () { return parseFloat(this); };` - http://jsfiddle.net/L4M2C/ – Ian Jun 19 '13 at 18:48
  • Yep you're right, I just completely overlooked it. `parseFloat(Lat).toFixed(2)` – Nubtacular Jun 19 '13 at 18:52

1 Answers1

5

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

Xotic750
  • 22,914
  • 8
  • 57
  • 79
  • 1
    There's not really that much controversy for changing the `String` prototype. Now, `Array` and `Object` are another thing... – Ian Jun 19 '13 at 18:59
  • I agree, but it depends on the circles you travel in. – Xotic750 Jun 19 '13 at 19:00
  • 1
    True, I've just never heard anything against it specifically. Something important though is checking that the method doesn't already exist. Like `"".parseFloat || String.prototype.parseFloat = function () { /* Stuff */ };` – Ian Jun 19 '13 at 19:02
  • Sure, in this simple case I didn't think it necessary but I will add it for completeness. – Xotic750 Jun 19 '13 at 19:03
  • And I hope the edits I just made were okay; feel free to revert or anything :) – Ian Jun 19 '13 at 19:03
  • Well, even in simple cases, you never know if it's there, so it can't hurt to encourage checking. No big deal :) – Ian Jun 19 '13 at 19:04
  • @Xotic750 what if I am trying to add two decimal the trailing zeros are missing! +(parseFloat(3.6 + 4.4).toFixed(1)) if I use .toFixed it returns string and parseFloat return number but without decimal point/trailing zero – Santosh Jan 07 '19 at 19:04
  • To have trailing zeros for display it has to be a string, that's just the way JS is. – Xotic750 Jan 09 '19 at 17:29