Kpower
Kpower

Reputation: 1257

Preserving decimals when reading from files in php

So I have a text document which is literally as follows

7
3
100
200.
300

and my code for reading from the file is:

$file = fopen("example.txt","r+") or exit("Unable to open file!");

$first = "" + fgets($file); $second = "" + fgets($file); $answers = array(); for ($x = 0; $x < $second ; $x++) { $answers[$x] = "" + fgets($file); } echo(answers[1]);

this results in 200 being printed out to the screen.

How do I preserve the decimal point in the line that outputs 200 but whose actual value is 200. ?

Upvotes: 0

Views: 57

Answers (1)

zerkms
zerkms

Reputation: 255015

In your original code you've been using a weird construction:

"" + $var

what it does as a result is implicitly converts both operands to numbers. Assuming $var = '200.'; the result of this expression will be float(200).

The 200. is not a number, but a string representation of a number. So if you want to leave it as it is - just don't convert it into a number.

Upvotes: 1

Related Questions