Javascript Method Chaining: Correct method chain toFixed() and parseFloat() to return a number, not a string?

StackOverflow https://stackoverflow.com/questions/17198970

  •  01-06-2022
  •  | 
  •  

Pregunta

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?

¿Fue útil?

Solución

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

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top