0

In a rails 5.2.0 and ruby 2.5.1 project I'm generating CSV files where there are a lot of decimal numbers, formatting them with number_to_rounded and using comma as decimal separator:

irb(main):006:0> number_to_rounded(tot_calculation, precision: 2, separator: ',')
=> "0,37"



irb(main):214:0> rows << [ number_to_rounded(p.import, precision: 2, separator: ','), number_to_rounded(p.last_value, precision: 2, separator: ','),number_to_rounded(p.percentage, precision: 2, separator: ',')]
=> [["110000,00", "110000,00", "0,46"]]

When exporting csv with

csv_data = CSV.generate(headers: true, col_sep: ';') do |csv|
  csv << headers
  rows.each { |row| csv << row }
end
data_csv.attach(io: StringIO.new(csv_data), filename: "#{Date.today.strftime("%Y%m%d")}_daily.csv", content_type: 'text/csv')

decimal separator used is dot instead of comma. I checked locale and it is :it as it should be.

csv_data is: ".......on\n110000,00;110000,00;0,46\n"

The plaintext of generated file is using dots: 0.00;943.84;943.84;90.00;100.00;117000.00;117000.00;

Decimals separated by dot

How can I make generated CSV using comma as decimal separator?

10
  • CSV means that whole values get separated by commas - E.g. 0.00, 943.84 The fact that individual values contain dots instead of commas like in 943.84 has to do with the locale that you are using in your env. Try changing the system locale and how numbers are displayed for that matter and check if it alters the value representations. Commented May 19, 2022 at 8:18
  • Locale is right, :it in this case. Commented May 19, 2022 at 8:25
  • Please paste the raw generated CSV output (the actual text), because I see that the values are in tabular format, which means that you have opened it with some 3rd party app. It happens that if you open a CSV with Excel for instance, it applies its own formatting on the values. Commented May 19, 2022 at 8:29
  • You have to add the formatted values, e.g. csv << ['0,00', '943,84']. Of course, you can use number_to_rounded to format them. Commented May 19, 2022 at 8:38
  • edit on the post Commented May 19, 2022 at 8:45

1 Answer 1

1

There's nothing special about commas, you just have to pass the formatted values as strings, e.g.:

csv_data = CSV.generate(col_sep: ';') do |csv|
  csv << ['1,95', '14,50']
  csv << ['2,75', '18,99']
end

File.write('test.csv', csv_data)

Content of test.csv:

1,95;14,50
2,75;18,99

Note that the values are not getting modified this way, i.e. commas and trailing zeros are retained.

You can of course use number_to_rounded to generate the formatted string values.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.