Changing a Drupal field from float to decimal when it has data
Drupal refuses to change the type of a field storage that already holds data, so you cannot switch a field from float to decimal through the UI or a config import. You can do it in a hook_update_N(): alter the database columns yourself, rewrite the field storage and field config directly, then tell the entity definition update manager that the column change has already been handled. If the float has already rounded values, repair them afterwards in a post-update function, from a source you trust.
The situation
On one member site of a group of nonprofit membership sites built on a shared Drupal distribution, organisations report a yearly total in whole currency units. The number is filled in from a form the organisation submits and is synced to a CRM. The field had been created as a plain Drupal float field, which is an easy choice to make for "a number" and works fine for small values.
Large values did not survive. A seven-digit total entered as one number was read back with its last digit changed. A teammate traced it to the column type and moved the field to decimal with a precision of 20 and a scale of 0, which stores and returns the exact integer.
Why a float field rounds large numbers
Drupal's float field stores its value in a normal-sized float column, which on MySQL is FLOAT: a 4-byte, single-precision number. It holds only about seven significant decimal digits, and MySQL returns FLOAT values rounded to fewer than that. You can see it without Drupal:
CREATE TABLE t (v FLOAT);
INSERT INTO t VALUES (1234567);
SELECT v FROM t; -- 1234570
Once Drupal loads that rounded value and the entity is saved again, the rounding is permanent. Money, counts and totals should never be floats. Use decimal for amounts with a fixed number of decimal places and integer (or decimal with scale 0 when the values may exceed a 32-bit integer) for whole numbers.
Why Drupal won't just change the type
Edit the exported field storage YAML from float to decimal and import it, and the import fails with "Cannot change the field type for an existing field storage." FieldStorageConfig::save() refuses the same change in code. Behind that, the entity schema handler refuses to alter the columns of a field that has data. Both are deliberate: core cannot know how to convert your data safely, so it makes you do it.
That means the change has three parts that core normally keeps in step for you, and you have to do each one by hand:
- The database columns, in both the field data table and the revision table.
- The configuration: the field storage (type and settings) and every field instance on a bundle (its
field_type). - The last installed schema, which Drupal compares against to decide whether entity updates are pending.
How to do it in one update hook
Here is the sequence as a fresh, minimal example for a field_annual_total field on the organisation bundle of nodes. It is idempotent, so running it twice does nothing the second time.
use Drupal\field\Entity\FieldStorageConfig;
/**
* Converts field_annual_total from float to decimal(20, 0).
*/
function example_update_10001() {
$storage = FieldStorageConfig::loadByName('node', 'field_annual_total');
if (!$storage || $storage->getType() !== 'float') {
return 'Nothing to convert.';
}
// 1. Alter the columns. Core will not do this for a field with data.
$mapping = \Drupal::entityTypeManager()->getStorage('node')->getTableMapping();
$column = $mapping->getFieldColumnName($storage, 'value');
$spec = ['type' => 'numeric', 'precision' => 20, 'scale' => 0, 'not null' => TRUE];
$schema = \Drupal::database()->schema();
foreach ([$mapping->getDedicatedDataTableName($storage), $mapping->getDedicatedRevisionTableName($storage)] as $table) {
$schema->changeField($table, $column, $column, $spec);
}
// 2. Rewrite the config directly, bypassing the entity save that forbids it.
$config = \Drupal::configFactory();
$config->getEditable('field.storage.node.field_annual_total')
->set('type', 'decimal')
->set('settings', ['precision' => 20, 'scale' => 0])
->save();
$config->getEditable('field.field.node.organisation.field_annual_total')
->set('field_type', 'decimal')
->save();
// 3. Update the installed definition without altering the columns again.
$config->reset();
\Drupal::entityTypeManager()->clearCachedDefinitions();
\Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
$updated = FieldStorageConfig::loadByName('node', 'field_annual_total');
$updated->setSetting('column_changes_handled', TRUE);
\Drupal::entityDefinitionUpdateManager()->updateFieldStorageDefinition($updated);
// Store the definition again without the temporary flag.
\Drupal::service('entity.last_installed_schema.repository')
->setLastInstalledFieldStorageDefinition(FieldStorageConfig::loadByName('node', 'field_annual_total'));
return 'Converted field_annual_total to decimal(20, 0).';
}
The step people usually miss is the third. Change the columns and the config but not the installed definition, and the status report flags mismatched entity and field definitions, because the installed schema still describes a float. The column_changes_handled setting is what core's SQL schema handler checks to accept a definition change whose columns have already been altered; storing the definition once more afterwards keeps that temporary flag out of the installed schema.
Commit the updated YAML for the field storage and the field alongside the hook, so the next config import agrees with the database instead of trying to change the type back.
Repairing values that were already rounded
Changing the column stops new damage but does not restore the digits already lost. The team repaired them in a hook_post_update_NAME() function, which is the right place for entity loads and saves, because by then the schema updates have all run.
What I like about their repair is how conservative it is:
- A trusted source. The correct number came from the most recent completed form submission for each organisation, not from a guess.
- Only values that could have been rounded. Totals below a million have fewer significant digits than the float can hold, so they were skipped.
- Only small differences. A stored value that differed from the submission by more than a small tolerance was left alone, on the assumption that someone had edited it by hand or it had come back from the CRM. A rounding error is a few units; a real edit is not.
- No side effects. Each repaired entity was saved with
setSyncing(TRUE), so the save did not trigger the real-time Salesforce push or other "on save" behaviour, and the function returned a list of what it changed for the deploy log.
That last point is easy to forget in any bulk repair. A data fix that fans out into emails, webhooks or CRM pushes stops being a data fix.
Key takeaways
- Drupal's float field uses a single-precision column on MySQL, so whole numbers of seven or more digits can come back rounded.
- Drupal will not change a field storage type once it has data, by config import or by saving the field storage entity.
- To convert one, alter the data and revision columns, rewrite the storage and field config, and update the installed definition with
column_changes_handledin a single update hook. - Repair already-damaged values in a post-update function, from a trusted source, within a tight tolerance, and with syncing enabled so saves do not trigger integrations.
- Choose
decimalorintegerfor money and totals from the start, because changing it later costs an update hook and a data repair.