in reply to Re^3: Issue getting value from text file and keep decimal
in thread Issue getting value from text file and keep decimal

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.
  • Comment on Re^4: Issue getting value from text file and keep decimal

Replies are listed 'Best First'.
Re^5: Issue getting value from text file and keep decimal
by Eily (Monsignor) on Jun 26, 2017 at 15:56 UTC

    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