# Views: how to remove ending zeros from decimal field

Suppose, we have a view with a decimal field:

It is output like this:

``````5 000.000
``````

Is it possible to remove the ending zeros, so it looked like this:

``````5 000
``````

But if there are meaningful values in the field, it should output all of them. For example:

``````5.100 -> 5.1
5.010 -> 5.01
5.001 -> 5.001
``````
• Look closer at your image..."The number of digits to the right of the decimal". Does that not have an option for 0? – Clive Aug 29 '14 at 8:13
• @Clive But I want it to output all 3 digits, if there are meaningful values. So, it should output: 4.001. But if the value is 4.030 it should output: "4.03". – user4035 Aug 29 '14 at 8:16
• Ah, you didn't mention that in that question. In that case I don't think so, you'd probably need to write a custom field handler for that (unless you can find a module that provides one, but it's quite a niche requirement so you might not get lucky) – Clive Aug 29 '14 at 8:20
• @Clive Thx, I improved the question. I'll write a template for that view field and use php to format the value. – user4035 Aug 29 '14 at 8:25
• I did, look at the upvote ;) – Mołot Aug 29 '14 at 8:43

I created a file /theme/bartik/templates/views-view-field--open-events--page--field-coefficient.tpl.php:

``````<?php
print (float) \$row->_field_data['id']['entity']->field_coefficient[LANGUAGE_NONE][0]['value'];
``````

And it worked.

You could write a custom field formatter in a custom module. See drupal-root/modules/field/modules/number/number.module and copy the related stuff for 'number_decimal' and adapt it to "trim_decimal".

``````number_field_formatter_info()
number_field_formatter_settings_form()
number_field_formatter_settings_summary()
number_field_formatter_view()
``````

In custom_module_field_formatter_view() define your formatter (here named: trim_decimal) like this:

``````...
case 'trim_decimal':
foreach (\$items as \$delta => \$item) {
\$output = number_format(\$item['value'], \$settings['scale'], \$settings['decimal_separator'], \$settings['thousand_separator']);

// If scale, we want to remove trailing 0 and the decimal separator,
// if there are no digits after decimal separator.
if (\$settings['scale']) {
\$output = rtrim(rtrim(\$output, '0'), \$settings['decimal_separator']);
}

if (\$settings['prefix_suffix']) {
\$prefixes = isset(\$instance['settings']['prefix']) ? array_map('field_filter_xss', explode('|', \$instance['settings']['prefix'])) : array('');
\$suffixes = isset(\$instance['settings']['suffix']) ? array_map('field_filter_xss', explode('|', \$instance['settings']['suffix'])) : array('');
\$prefix = (count(\$prefixes) > 1) ? format_plural(\$item['value'], \$prefixes[0], \$prefixes[1]) : \$prefixes[0];
\$suffix = (count(\$suffixes) > 1) ? format_plural(\$item['value'], \$suffixes[0], \$suffixes[1]) : \$suffixes[0];
\$output = \$prefix . \$output . \$suffix;
}
\$element[\$delta] = array('#markup' => \$output);
}
break;
``````