in reply to Re: Need some wisdom on strings to numbers
in thread Need some wisdom on strings to numbers

Hi there,

Thanks all for the prompt reply. I am passing the hash to an in-memory database (MongoDB) which serializes the hash into a json style structure. This causes the first variable (123) to remain as an int but the second one 123.1 gets in as a string and I think this is because the hash stores this value as a string. Any suggestions?

  • Comment on Re^2: Need some wisdom on strings to numbers

Replies are listed 'Best First'.
Re^3: Need some wisdom on strings to numbers
by decebel (Acolyte) on Oct 07, 2009 at 03:58 UTC
    As an afterthought to Alex's reply, is there a work around when we are serializing the data structure?

      Is it actually a problem that JSON is making 123.1 into a '123.1' as it goes into mongodb? If you are pulling it back out again in perl, then it shouldn't matter.

      If it does matter, then the workaround is going to be dependant on what library does the serialization. If it is JSON.pm, then what you are doing ( add zero, or multiply by 1 ) should make sure that things are encoded as numbers.

      It appears that JSON.pm is doing things correctly.

      use JSON::PP; use JSON::XS; use JSON::Syck; my $x = 123.1; my $y = '123.10'; my $z = $y + 0; my $h = { x => $x, y => $y, z => $z }; print JSON::PP::encode_json($h) . "\n"; print JSON::XS::encode_json($h) . "\n"; print JSON::Syck::Dump($h) . "\n"; __END__ {"y":"123.10","x":123.1,"z":123.1} #JSON::PP {"y":"123.10","x":123.1,"z":123.1} #JSON::XS {"y":123.10,"x":123.1,"z":123.1} #JSON::Syck ( seems to do $y wrong/ +differently )
      -- AlexLC