0

I would like to ensure that the numeric fields in my data table always show 4 decimal places. The numeric fields need to remain numeric fields.

Secondly, when exporting the data to CSV, the numeric fields should always export with 4 decimal places.

I have imported a large .csv data file. It contains both numeric and text fields. I would like this data to always be displayed with 4 decimal places in the data table.

Also when exporting the data, it must be exported with decimal places in tact.

Currently I have used the following code:

library(formattable)
data$OS_BALANCE <- formattable(data$OS_BALANCE, digits=5, format='f')
data$OS_ACCRUAL <- formattable(data$OS_ACCRUAL, digits=5, format='f')

But when I rename variable the formatting disappears.

OTStats
  • 1,820
  • 1
  • 13
  • 22
Manfred
  • 147
  • 2
  • 10
  • You need to understand the difference between how many decimals are printed vs how many are stored. If you want the fields to be numeric (and you should!) you essentially *cannot* control how many decimals are stored because the numbers are stored in binary, not in decimal. [This FAQ has good info on that concept](https://stackoverflow.com/q/9508518/903061). Once you understand that, I think this question is a duplicate of [Controlling number of decimal digits in print output in R](https://stackoverflow.com/q/2287616/903061). – Gregor Thomas Sep 17 '19 at 15:37
  • Thank you. That is understood. I guess my question is more around exporting a data to a csv file and ensuring that the numeric fields are exported with 2 decimal places – Manfred Sep 17 '19 at 18:53
  • So, in that case, your *"numeric fields need to remain numeric fields"* doesn't apply since CSV doesn't have data types. Convert to `character` using `format` to control the number of decimals (the [FAQ on formatting decimals can help, if you need it](https://stackoverflow.com/q/3443687/903061)), then write your CSV. You can use `quote = FALSE` in `write.csv()` so nothing is quoted, if you want. `data.table::fwrite` has smarter defaults, so you wouldn't need to touch the `quote` argument. – Gregor Thomas Sep 17 '19 at 19:24

0 Answers0