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.
| [reply] [d/l] |
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.
| [reply] |
As I said, I think using Number::Format is a good idea. In all cases, I would advise to consider that you have a (simple) number everywhere (even if it's actually a string, since perl will do the translation for you), and only add the formatting at the last moment when printing.
By default Number::Format works with an OO interface, but you can bypass that by adding the :subs flag. The :vars flag would be needed to change the parameters (eg: thousands separator) but the default values are actually the ones you want.
use Number::Format qw(:subs);
print format_number(123456.789); # prints 123,456.79
I told you about the fact that perl will turn the string "123,456" into the number 123 (because it doesn't interpret thousands separator), Number::Format also provides a unformat_number to correctly translate such a string into the expected number.
Edit: my bad, to have trailing zeros you can use the optional parameters of format_number, which are the precision and trailing zeros:
use Number::Format qw(:subs);
print format_number(123456, 2, 1); # print 123456 with two decimals, f
+ill with 0s
| [reply] [d/l] [select] |