문제

I have a line of code which says --

var latitude = JSON.stringify(place.lat);

when I do alert(latitude) -- It gives me output "33.232342" .But I want the number so when I do

var latitude = parseFloat(JSON.stringify(place.lat));

I get NaN. Could someone tell me what the problem might be?

Thanks

도움이 되었습니까?

해결책

Your place.lat is already a string. So doing JSON.stringify() makes ""33.232342"".
Just:

parseFloat(place.lat);

다른 팁

The problem is that place.lat is a string, so when you stringify it, you get a string with quotes.

That's the same result than with

parseFloat(JSON.stringify("3.5"))

that is

NaN

A solution would be to directly parse place.lat : parseFloat(place.lat)

If you want to parse a number which is in a string with quotes, you may also do

parseFloat(str.slice(1,-1))

The problem roots here:

JSON.stringify(place.lat) returns "' 20.0120132312'", which has a leading ' in it. Just use:

parseFloat(place.lat);

Why are you JSON.stringifying it if it's already an object?

Just do parseFloat(place.lat).

You have to invoke:

parseFloat(JSON.parse(latitude))

JSON.stringify turns primitives into strings, so:

JSON.stringify(5.1)

returns the 5-character string

"5.1"

Passing such a value into parseFloat results in NaN. Simply don't JSON.stringify the value, and your code should work fine.

It's worth noting that the JSON spec only allows objects and arrays as top-level elements in a JSON representation, so it's not spec-compliant to "JSON-ify" a raw number (but your browser will do it anyway).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top