in reply to Issue getting value from text file and keep decimal

The issue is that you go back and forth between number and string representation. In $main_balance = $main_balance - $debit; the minus is a numeric operation, so perl translates your string into numbers, where the number of displayed digits is not memorized. Your format function turns it back into a string, but the formatting already has been lost.

I think your best option is Number::Format, which will output the expected format wheter the input is already a number, or a string representation (if the string doesn't already includes thousands separator, "900,000" will be interpreted as the number 900).

Also the sigil @ is used to fetch several elements, and $ a single one. So even if you are using a single element from an array, $ has to be used (see perldata). The second element of the array @fields should therefore be $fields[1] instead. Perl will actually complain about this if warnings are activated (which they should be).

Edit: turned $fields1 into $fields[1], thanks AnomalousMonk

Replies are listed 'Best First'.
Re^2: Issue getting value from text file and keep decimal
by jason.jackal (Novice) on Jun 26, 2017 at 15:09 UTC
    HI Eily, Thank you for your help, but I am a little confused. I thought I declaring a decimal/float with 0.00 already. And when the loop goes and reads in 900000.00 it is already reading in another decimal or float. The was my thinking anyway, and why I thought I had to change in a decimal/float to a string so I could insert the comma. The idea was to keep the math and decimal in one variable and write out the product to a string.

      The two digits after the decimal points are part of the formatting of the string, but a float contains only the value, without any concept of format or display. So when perl has to extract the value from the string "900000.00" to be able to make mathematic operations on it (the substraction), the formatting information is lost.

      The confusion might come from the fact that you think you have a float in the first place, when you have instead a string, because perl will (edit: almost) seemlessly turn one into another to make life easier for you, so although your $main_balance is a string before $main_balance = $main_balance - $debit;, it will have been replaced by a number after that line.

        Hi Eily, Yes... That could be my first problem thinking that I had decimal/float in the first place. So I should use the sprintf to always convert a string if in this case "900000" to a float 900000.00 and then use the regex string to add the comma? thank you.