Converting strings to floats

perl

Solution

You are correct to say that multiplying a string by 1 will force it to be evaluated as a number, but the numeric `!=` comparator will do the same thing. This is presumably a technique you have acquired from other languages as Perl will generally do the right thing and there is no need to force a cast of either operand.

Lets take a look at the values you're comparing:

use strict;
use warnings;

use Data::Dumper;

my $price = '8.5';
my $lsec = '8.5';

my $rounded_price = sprintf("%.2f", ($price * 100 + 0.5) / 100);
print "$rounded_price <=> $lsec\n";

if ( $rounded_price != $lsec ) {
  print Dumper($price,$lsec);
}

output

8.51 <=> 8.5
$VAR1 = '8.5';
$VAR2 = '8.5';

So Perl is correctly saying that 8.51 is unequal to 8.5.

I suspect that your

($price * 100 + 0.5) / 100

is intended to round `$price` to two decimal places, but all it does in fact is to increase `$price` by 0.005. I think you meant to write

int($price * 100 + 0.5) / 100

but you also put the value through `sprintf` which is another way to do the same thing.

Either

$price = int($price * 100 + 0.5) / 100

or

$price = sprintf ".2f", $price

but both is overkill!

Problem

could soemone help me with the following condition, please? I'm trying to compare $price and $lsec. ``` if( (sprintf("%.2f", ($price*100+0.5)/100)*1 != $lsec*1) ) { print Dumper($price,$lsec) } ``` Sometimes the dumper prints same numbers(as strings) and jumps in. Thought, that multiplying with 1 makes floats from them... Here dumper output: ``` $VAR1 = '8.5'; $VAR2 = '8.5'; ``` What am I doing wrong? Thank you, Greetings and happy easter.

Original source