Is there a way to change the number type once a field has been created in the attribute table in QGIS? I selected 'Whole number (integer)' initially but now need to switch to 'Decimal number (real)' in order to limit the number of decimal places to 1. I've already filled in all the rows of the column and so I'm wondering can I change the type and covert the existing numbers to a single decimal place or do I have to create a new field column selecting decimal from the start?
3 Answers
Use the tool "Refactor Fields" in QGIS processing algorithm.
Select the layer and set the type of the column you want to convert to Decimal nummber ( Length is the total length of the number, precision the decimal part). Click on run and a temporary layer will be loaded which has the fields as you wanted them to be (check the attribute table/layer properties to verify your results!). Close your original layer, and save the temporary one over the existing one - done
-
1
The easiest way is to create a new field and copy all values from the old to the new field - this can be done in one single step and is almost as easy as it would be if you could just switch the field type.
Use the field calculator to create a new field and type as expression to_real( "your_old_field")
Replace the your_old_field
part with the name of the integer-field where you initially have stored the values you now want to copy. Click OK and you're done. Toggle edit mode to save the changes!
With SQLite changing the type of an attribute requires that a new table is created with edited schema, data are copied from old table into the new one, and the old table is finally dropped. See https://sqlite.org/lang_altertable.html for noticing that "modify datatype" is not supported directly by ALTER TABLE and https://stackoverflow.com/questions/2083543/modify-a-columns-type-in-sqlite3 that gives a few alternatives about how to change the datatype by other means.
GeoPackage has quite a many triggers and I do not feel totally safe with manipulating the database by using generic SQLite tools, but if you are brave enough you can try DB Browser for SQLite. Make a backup copy of your GeoPackage first. I had a try with a dummy GeoPackage and changing datatype from integer into real seemed to be successful and also QGIS shows the attribute as real now.
to_real("oldfieldname")
in fieldcalculator or via refactor fields processing tool.