Gravity Wiz

Magically enhanced tutorials, snippets and plugins for Gravity Forms!

  • Gravity Perks
    • Gravity Perks
    • Tutorials & Snippets
    • About
  • Support
    • Documentation
    • Support
    • Account

Format Field as Currency

This snippet provides a simple method for formatting your fields as currency.

Last updated November 27, 2019 | Written by David Smith 91 Comments

  • November 8th, 2013: Updated to fix issue with non-US currencies.

  • September 21, 2013: Updated snippet as a class. Added support for using with number fields.

  • May 21, 2013: Updated to also format field value as money when value retrieved (i.e. merge tags, entry edit).

  • March 15, 2013: Updated to enqueue gravityforms.js if the form has not already enqueued it.

Show All Updates
This snippet still works; however, it is possible to achieve the same effect with Gravity Forms v1.8. Create a Number field and selected “Currency” from the “Format” setting.

Install the snippet and then apply the gf_money to your fields CSS Class field in the Gravity Forms form editor.

This is particularly useful when combined with Gravity Forms new calculation functionality to generate subtotals on your WordPress forms!

Simple Version

If you aren’t super comfortable with javascript and would prefer to just copy and paste this functionality into your theme’s functions.php file, this snippet will do the trick.

Show CodeDownload Code
<?php
/**
* Format Fields as Currency via jQuery
* http://gravitywiz.com/format-field-as-currency/
*/
class GWFormatMoney {
/**
* Stores a copy of the original field values so once the money-formatted numbers have been cleaned for validation
* they can be restored after being validated.
*
*/
var $_field_values = array();
function __construct() {
add_filter( 'gform_pre_render', array( $this, 'format_money_js' ) );
add_filter( 'gform_pre_validation', array( $this, 'clean_value_for_number_fields' ) );
add_filter( 'gform_validation', array( $this, 'restore_value_for_number_fields' ) );
add_action( 'gform_get_field_value', array( $this, 'format_money' ), 10, 3 );
}
function format_money_js($form) {
$this->enqueue_gravityforms_js();
$script = '(function($){' .
'$(".gf_money input").each( function() { ' .
'$(this).val( gformFormatMoney( $(this).val() ) ); ' .
'}).change( function( event ) { ' .
'$(this).val( gformFormatMoney( $(this).val() ) ); ' .
'}); ' .
'gform.addFilter( "gform_calculation_format_result", "gwMaybeFormatMoney" ); ' .
'window.gwMaybeFormatMoney = function( returnVal, origResult, formulaField, formId ) { ' .
'var field = jQuery("#field_" + formId + "_" + formulaField.field_id); ' .
'return field.hasClass( "gf_money" ) ? gformFormatMoney( origResult ) : returnVal; ' .
'} ' .
'})(jQuery);';
GFFormDisplay::add_init_script( $form['id'], 'format_money', GFFormDisplay::ON_PAGE_RENDER, $script );
return $form;
}
function format_money( $value, $lead, $field ) {
$css_classes = explode( ' ', rgar( $field, 'cssClass' ) );
if( ! in_array( 'gf_money', $css_classes ) )
return $value;
require_once( GFCommon::get_base_path() . '/currency.php' );
$currency = new RGCurrency( GFCommon::get_currency() );
$value = $currency->to_money( $value );
return $value;
}
function clean_value_for_number_fields( $form ) {
foreach( $form['fields'] as $field ) {
$is_number_field = GFFormsModel::get_input_type( $field ) == 'number';
$has_gf_money_class = in_array( 'gf_money', explode( ' ', rgar( $field, 'cssClass' ) ) );
if( ! $is_number_field || ! $has_gf_money_class )
continue;
$value = $_POST["input_{$field['id']}"];
if( ! $value )
continue;
// save original value to be restored later
$this->_field_values[$field['id']] = $value;
require_once(GFCommon::get_base_path() . '/currency.php');
$currency = new RGCurrency(GFCommon::get_currency());
$_POST["input_{$field['id']}"] = $currency->to_number( $value );
}
return $form;
}
function restore_value_for_number_fields( $validation_result ) {
foreach( $validation_result['form']['fields'] as $field ) {
if( ! isset( $this->_field_values[$field['id']] ) )
continue;
$value = $this->_field_values[$field['id']];
// @REMOVE: since the original value will already be in the money format, no need to reformat here
// leaving in place for a few weeks to ensure no issues come up with the removal
// require_once(GFCommon::get_base_path() . '/currency.php');
// $currency = new RGCurrency(GFCommon::get_currency());
// $currency->to_money( $value );
$_POST["input_{$field['id']}"] = $value;
}
return $validation_result;
}
function enqueue_gravityforms_js() {
$has_proper_support = version_compare( GFCommon::$version, '1.8.dev4', '>=' );
$enqueue_script = $has_proper_support ? 'gform_gravityforms' : 'gforms_gravityforms';
if( ! wp_script_is( $enqueue_script ) )
wp_enqueue_script( $enqueue_script );
}
}
new GWFormatMoney();
view raw gw-format-money.php hosted with ❤ by GitHub

Slightly Less Simple Version

If you’re comfortable with javascript/jQuery, here is the javascript-only version. Be sure whichever javascript file you include this in is also included on the page you are displaying your Gravity Form.

This method has been removed in favor of the updated “Simple Version” above. The simple version takes advantage of new Gravity Forms developer functionality to enqueue the script only when needed and in a GF-friendly method.

Filed Under: Deprecated

Comments

  1. Drs. Andor Demarteau says

    February 15, 2019 at 2:19 pm

    Would it be possible to change this snippet to do the following: – rewrite the label (not the value) of a radio or dropdown selection to have a date displayed as 15 February 2019 where as the input and value remains 2019-02-15 probably won’t work for date fields I suspect.

    Reply
  2. Rafal says

    October 4, 2017 at 7:23 am

    I’m getting a weird result after applying this code:

    The field I’m trying it on had this value before I applied the “gf_money” class onto it: 349.65 After adding that class I got: 34.965,00 ( looks like it’s multiplied by a 100… )

    This could be to do with the “Number Format”. I have that number field set to this: “9,999.99” which I need to keep and the price shown after using the code looks like it’s in the other format: 9.999,99

    Another one is that while the original price of 349.65 changed to 978.6 – it had .6 not .60 which looks like it caused the number to look like it was multiplied by 10 this time instead of 100. After I added an additional option onto it but with the class it was 9.786,00

    Reply
    • Rafal says

      October 4, 2017 at 7:28 am

      I got it fixed by changing (EURO) to US Dollars in the main GF settings. Seems that the previous fix to non-US currencies either doesn’t work or did not cover € (EUR)

    • Rafal says

      October 4, 2017 at 7:42 am

      I’ve just hit another wall with this implementation: While the price is now showing ok (without the currency symbol) It’s being submitted with one. The notification email that’s sent out has that $ too (which I can live with) but the worst part is that I’m passing parameters onto a summary page and this is what’s being passed: &oohppv=%2524978.60 and when I try to print that “oohppv” value on my summary page I get this: “%24978.60”

      Any way to submit that value as currency but fully remove the currency symbol?

    • David Smith says

      October 28, 2017 at 9:33 am

      You would need to use url_decode() on the value.

  3. Sam says

    January 5, 2017 at 2:48 pm

    Thanks for this code! The Number field that is now available with gravity forms looks like it does the same thing however when sending the data to a 3rd party like google sheets the GF Number field sends the original number that was entered instead of the formatted one. This snippet however sends the formatted number with dollar sign and cents!

    Reply
    • David Smith says

      January 5, 2017 at 3:18 pm

      Hi Sam, thanks for sharing your use-case! :)

  4. Michael says

    January 16, 2016 at 2:35 pm

    There is a comment regarding this issue, but it wasn’t fully answered.

    1. How can I apply this snippet to a list field column (and all subsequent rows within that column). So that it formats to a currency.

    2. I would be using this snippet to get halfway to what I really want to accomplish — which is to add all items within a specific column to populate a total in another field.

    Currently gform_column_input does not support a number field =(

    Any help appreciated.

    Reply
    • David Smith says

      March 25, 2016 at 12:58 pm

      Hi Michael, I don’t currently have a solution for this.

  5. Max says

    June 19, 2014 at 4:26 pm

    I need adjust the formatting, in my use of this snippet I don’t need the cents places, just the whole numbers. So instead of $1,000.00 I need: $1,000 Can I adjust to get this result?

    Reply
  6. Dan says

    March 19, 2014 at 3:32 pm

    David, I tried adding this snippet to the functions.php file and adding the gf_money class to the field but this doesn’t seem to work when using the Custom Field field for the GF Post Fields. The currency is formatted correctly from the Merge Tag in the Email but when I view the Custom Field from the created Post’s Edit Post page, the currency is not formatted correctly.

    Example: $1,800.00 becomes 1800.00 in the Custom Field

    Any ideas?

    Reply
    • David Smith says

      September 10, 2014 at 11:04 pm

      This functionality is now available with Gravity Form “Number” fields under the “Format” setting.

  7. sergey says

    January 4, 2014 at 3:04 pm

    if insert code the template crash!

    Reply
    • David Smith says

      January 5, 2014 at 11:32 am

      Hi sergey, most issues like this are caused by either a) failing to copy the entire snippet to your theme’s functions.php file or b) the code requires a more recent version of Gravity Forms. The latter issue really should be accounted for on my end within the snippet and will be moving forward with new snippets. Did you receive an error message?

    • sergey says

      January 6, 2014 at 4:42 am

      The gravityform is the last.

      The template the problem is not show entire, parts of template not charge.

      How too support for this issue? is possible send mail?

  8. Rens says

    December 16, 2013 at 4:32 pm

    Hello David,

    I would like to combinate this function with the functions: https://gravitywiz.com/calculate-number-of-days-between-two-dates/

    But if add both in the functions.php only the currency functie works.

    Do you know what the problem is?

    Thanks in advance!

    Reply
    • David Smith says

      December 16, 2013 at 6:29 pm

      Do you have a link to a form where I can see both of these implemented?

    • Rens says

      December 17, 2013 at 5:23 pm

      Hello david,

      Thanks for you’re fast reply, you’re remark dit the trick.

      It was exaclty what you said, I used it in 1 form and both functions are working correclty now.

      The problem was when I used the currency in an another form then the number of days functions. Only the Currency form works.

  9. Steve says

    December 5, 2013 at 6:41 pm

    I wanted to share a quick and easy CSS fix for this I implemented.

    1. Add price_me as a class to your number field

    2. Add the following to your CSS:

    .price_me input{background:none; border:none; color:darkgreen;}

    .price_me .ginput_container:before {content:’$ ‘;margin-right:2px; color:darkgreen; }

    Hope that helps someone.

    Reply
    • KW says

      December 9, 2013 at 11:40 am

      Brilliant, thanks, Steve! Why did I not think to do it with CSS!

  10. Steve says

    December 5, 2013 at 6:26 pm

    Thanks for the cool snippet! Unfortunately, it doesn’t seem to work on my form for WP 3.7.1 & GF 1.7.12. It breaks any form with a number field and the gf_money class. The form displays no fields when in preview mode in the admin. I’m also using GF PDF Extended in case that’s helpful. Cheers.

    Reply
    • David Smith says

      December 5, 2013 at 6:41 pm

      Hey Steve, this is resolved in the latest GF 1.7.12.3 which you can get by contacting Gravity Forms support. It is also working in the latest GF 1.8 beta which you can download here.

  11. Rupert Cross says

    November 7, 2013 at 9:20 am

    Hi,

    Great snippet. I can get it working perfectly using dollars, but when I change the format to pounds sterling it add 163 to the price so rather than £500.00 I get £163,500.00

    Any thoughts?

    Thanks!

    Reply
    • David Smith says

      November 8, 2013 at 7:53 am

      Per our email exchange, this snippet has been updated to resolve this issue.

  12. LM says

    October 16, 2013 at 2:20 pm

    I know support for number fields was recently added (and it does work), however when “calculations” are enabled on a number field the form breaks and does not display (due to conditional logic used in the form).

    Do calculation enabled number fields work on your end?

    Reply
« Older Comments

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Categories

  • How To (34)
  • News (21)
  • Plugins (8)
  • Releases (7)
  • Resource (2)
  • Snippets (53)
  • Tutorials (42)
  • Updates (80)

Recent Posts

  • Complete Guide to Gravity Forms WooCommerce Integration
  • Gravity Wiz Weekly #80
  • Complete Guide to Gravity Forms Conditional Logic
  • Exporting with Nested Forms
  • Gravity Wiz Weekly #79

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Copyright © 2019 · Powered by WordPress · Gravity Wiz LLC · Log out

  • Support
  • Affiliates
  • About
  • Sitemap
  • Gravity Perks
    ▼
    • Gravity Perks
    • Tutorials & Snippets
    • About
  • Support
    ▼
    • Documentation
    • Support
    • Account