June 6, 2020: Removed a rogue JS debugger statement.
Let’s say you sell business cards. Orders for these business cards must be placed in increments of 500. If you try to order 499 cards, you’re going to get 500. If you try to order 600, you’re going to get 1000 (the next increment of 500). Do you see how this works?
This snippet provides a way to round field values (particularly for Number, Quantity, and Calculation fields) up to the nearest specified increment. In addition, it provides a way to cap the increment and set a minimum.
- How do I install this snippet?
- Usage Instructions
- Custom Rounding CSS Class
- In closing
- Taking It Further
- Known Limitations
How do I install this snippet?
- You will want to be running at least Gravity Forms v.1.8 though it may work with some older versions.
- Already have a license? Download Latest Gravity Forms
- Need a license? Buy Gravity Forms
- Copy and paste the snippet into your theme’s functions.php file.
- This snippet requires no other configuration in the code. Continue reading for usage instructions.
Usage Instructions
This snippet is powered by special CSS classes which can be applied to a field via the “CSS Class Name” setting. Here are step by step instructions:
- Open your form for editing.
- Open the fielding settings for the field you would like to round incrementally.
- Navigate to the “Advanced” tab.
- Select the “CSS Class Name” setting and add the “gw-rounding-n” class, replacing n with the increment to which you would like this field to round.
All Options
gw-round-n | round to the nearest increment; will round up or down to the nearest increment example: gw-round-100 would round 1 to 0, 149 to 100, 150 to 200, etc |
gw-round-up-n | round up to the nearest increment; will always round up example: gw-round-up-50 would round 1 to 50, 511 to 100, 149 to 150, etc |
gw-round-down-n | round down to the nearest increment; will always round down example: gw-round-down-25 would round 1 to 0, 26 to 25, 51 to 50, etc |
gw-round-min-n | round up to the specified minimum if not reached example: gw-round-min-50 would round 1 to 50, 49 to 50, 51 and greater would not be rounded |
gw-round-max-n | round down to the specified maximum if exceeded example: gw-round-max-250 would round 251 to 250, 400 to 250, 250 and below would not be rounded |
gw-round-custom-n | round based on a custom function example: See the Custom Rounding CSS Class section. |
What if I’m already using the “CSS Class Name” setting for another CSS class?
No problem. The “CSS Class Name” setting supports multiple classes and that won’t interfere with the special “gw-round-n” class. Just add a space after the last class and add the “gw-round-n” class after it.
Does this work with decimals?
Yup! You can use decimal values in any of your rounding classes (e.g. gw-round-2.5
to round in increments of 2.5
).
Custom Rounding CSS Class
Rounding by Increments also supports custom rounding methods using the gw-round-custom
CSS class. Custom rounding methods require implementing the math to handle the rounding both in PHP and JavaScript. The PHP will go into your theme’s function.php file and for the JavaScript portion we recommend using our free Custom JavaScript plugin.
Below is an example of how you can use a custom rounding function to round to the nearest 9th number. First is the PHP portion that handles the calculation on the back-end:
// Include the following code in your theme's functions.php or using a custom snippet manager.
add_filter( 'gw_round_nearest9', function( $value, $rule ) {
return round( $value / 10 ) * 10 - 1;
}, 10, 2 );
And this is the JavaScript to handle the calculation on the front-end:
window.gform.addFilter( 'gw_round_nearest9', function( value, rule ) {
return Math.round( value / 10 ) * 10 - 1;
});
The filter’s name corresponds to the CSS class you’ll use on the field to activate the custom rounding. Simply take the function name and replace the underscores with dashes for the CSS class. In the case of the example functions above, the CSS class is gw-round-nearest9
.
In closing
You know the drill. If you like it, use it, or improve it, let us know!
Taking It Further
Use Rounding By Increments to Enforce Min/Max Product Totals
Say you have a form where you want to enforce a minimum or maximum total price for a product. For example, say I have a store that sells bulk widgets that has a minimum order of $500. Any number ordered that totals less than $500 is automatically rounded up to $500. On top of that, any amount ordered that totals more than $35000 is automatically rounded down to $35000. Here’s how you would set that up.
First, add a Number field to your form. This is where the user will insert the quantity of widgets they are purchasing.
Then, add a Product field. Give this Product field name like “Widget Total”, set the Field Type to Calculation, and check Disable quantity field. For the calculation, insert the merge tag for the Number field above and multiply it by your unit price.
Then, go the Appearance tab of the Product field and insert the gw-round-min-n
and gw-round-max-n
merge tags. Set the values of the merge tags to your minimum and maximum product total.
If a user buys a quantity that would total less than $500, it’s automatically rounded up, and vice versa for anything above $35000.
Known Limitations
- This snippet does not support Total or Product price fields.
Did this resource help you do something awesome with Gravity Forms?
Then you'll absolutely love Gravity Perks; a suite of 46+ essential add-ons for Gravity Forms with support you can count on.
Can we combine rounding with a minimum? gw-round-2-min-0. I’ve tried this but it doesn’t appear to be working.
Hi Martin,
Yes, you can use multiple rounding CSS classes in the same field, like this:
gw-round-2 gw-round-min-0
I want to round to the nearest number to eliminate decimals, I can’t find how to do it
Hi Nury,
This tutorial should work in case you are working with Pricing fields: https://gravitywiz.com/how-to-add-three-decimals-with-gravity-form-currencies/
With Number fields, you can set the decimals points in the Gravity Forms field editor natively.
Best,
Hi,
i try to use your snippet for rounding. I install the Plug in and put the code in the function.php. I delete the opening <?php from the snippet and the closing php from the theme. But there are some Errors? Can you help me please?
Fatal error: Cannot declare class GW_Rounding, because the name is already in use in /home/netsh101145/html/xxx-demo/wp-content/themes/twentytwenty-child-theme/functions.php on line 31
Here is the snippet that i use.
http://snippi.com/s/eda7pr6
Best Jens
Hi Jens,
If you have the plugin installed, then you do not need to insert the snippet into your function.php file. The Plugin and the snippet are the same. The error you’re seeing is a result of trying to use both at the same time. So you should be good to go with just the plugin.
Best,
Hello —
I’m trying to install the Rounding Increments snippet and am having problems.
1) I installed the plug-in and entered my setting into Custom CSS Class — gw-round-up-1. I got a screen white-out of the form. Removing the CSS setting restored the form.
2) I tried copying the plain text code into a PHP snippets page (a plug-in used to add PHP without touching functions.php). I got the message that the snippet could not activate because of an error on line 341.
There is nothing on line 341. Here is the section of code where line 341 is located. Line 341 is the blank second line in the code below.
I am already subscribed to Gravity Perks. Is this snippet in that package?
We use Gravity Forms to score questionnaires. We would like to be able to round up amounts less than 1 to 1.
Thanks.
Vivian
Hi Vivian,
This is quite strange. Since you’re already subscribed to a Gravity Perk License, could you drop us a line through our support page here. 😃We’ll be happy to provide additional support for the snippet via the support form.
Hi I love this and need it, but when I install it and add the CSS class to a field it hides the entire form.
I copied the code, added it to my child’s functions.php and when I add the CSS to the field and click preview form it’s empty. I inspect element and there’s a element display: none Is there a step missing?
Hello Jimmy, can you make sure the snippet is installed correctly using these steps.If everything looks good could you try using the Plugin version and see if that resolves your issue. Let us know the result
I’ve tried loading this onto the form I’m working on but none of the rounding is happening. I have tried on 2 different sites and I’ve even created a basic form with a single number field with a “gw-round-100” css class added. None of them are working. An error is happening on the page when it hits this code http://snippi.com/s/2vix6ok (~line 161) of the gw-gravity-forms-rounding.php file.
I have tried attaching the rounding classes to a few different fields without success. I’ve tried “Number”, “Product”, “Quantity” and “Total” fields.
I don’t believe I’m doing anything incorrectly but nothing is happening. As I said, I’ve tried it on 2 different sites on 3 different forms including one that is only a single “Number” field with the ‘gw-round-100’. I’ve also tried different classes with the same result.
Not sure what else to try. I’ve used a few different snippets from GravityWiz over the last couple years without issue. This is the first one I’ve had any issues with.
Any other ideas to try?
Thanks.
Hello Neil, could you send us a snippi of the full code that you are using on your site? Are you using the plugin install or are you putting the code inside of your themes functions.php? I see that the demo site is still displaying it correctly. Let us know!
Hi Ryan,
I just copied and pasted into the functions file. When that didn’t work I removed that and added it as a plugin and activated it.
I didn’t change any of the code at all.
In the functions file (child-theme) there is only the enqueue function to pull in font-awesome and custom css.
I will try on another server to see if its something weird happening. Can you send me what you have that’s working and I can try that? I’m assuming it’s the same as what is in the zip file but who knows. It’s very weird. I also noticed that Gravity Forms isn’t rendering Number fields as actual number fields (type=”Number”) with increment arrows but instead as type=”text”. Shouldn’t have anything to do with this as I’ve tried in a variety of field types without success.
Thanks
Hello Neil, I used this code http://snippi.com/s/tnl23fe which is the same code but does not include the PHP tag on the top. We have a demo page found here that shows how it works. Please note that after adding the code you will need to select the “CSS Class Name” setting and add the “gw-rounding-n” class, replacing n with the increment to which you would like this field to round.
Hi Ryan,
That’s exactly what I’ve been doing. I’m getting a JS error in ChromDevTools “Uncaught TypeError: Cannot read property ‘length’ of undefined” which tracks back to line 11 here http://snippi.com/s/7a25m3l
This is on a brand new clean installation of WordPress with only GravityForms (latest version) installed. Using the TwentyTwenty theme.
I have added both of these classes to a Number field. gw-round-100 gw-rounding-100
With the error in the JS happening the form doesn’t even load. I’m left with a blank page.
Let me know if you need any additional info.
Thanks
Hey Neil, Thanks for that update. We have since updated the snippet and you should be able to now use it properly. Go ahead and copy the snippet again and see if this resolves your issue. Thank you for you patience. 😃
Have used this script for a few years – its been a great help thanks.
Now i´ve started to fill out my forms dynamically using a URL query string.
The form rounds to the nearest 100 in most cases – but when the value is set to 1000 the form chooses the preset value. ? (ignores the input from the string)
If the string value is 999 it rounds up to 1000.
Is the script somehow restricted to 3 digits and how can i fix this.?
The string used: ?value1=2&value2=1000
Hello Jesper, the script is not restricted to 3 digits. There could be a number of things happening here. If you have a cache, this may be aggressively caching the page and not catching the whole query. Another question is where are your values being populated from? From your example, it looks like value1 and value 2 already are predefined? What CSS Class Name option are you using to round within your form? If you are a Gravity Perks License holder we would be more than happy to take a deeper dive into your forms. Drop us a line through our support page here. 😃
I love this snippet, we use it a lot throughout our forms but can you tell me is there any way to round to the nearest increment of less than 1 but greater than 0? For instance, I tried to use gw-round-up-0.1 but it doesn’t seem to work. Is there any way to accomplish this?
Hi Jon, rounding by decimals is not supported currently. You could handle this by utilizing Copy Cat. Drop us a support request after purchasing a Gravity Perks license and we can walk you through it.
Hi and first of all thanks a lot for your precious work! I’ve been using the “Rounding by Increments with Gravity Forms” snippet (without the GP plugin) for a few month and it was working really great here: https://delair.aero/delair-ux11-project-calculator/ But recently (I don’t know when exactly) it stopped working. This Gravity form is used to give information about our professional drones including the number of flights needed for customers projects. Therefore the number of flights should always be equal to 1 at least (it can’t be equal to zero), so I used the “gw-round-up-1” CSS class but it seems to be kind of broken now and I can’t figure out how to fix it… Your help wold be very appreciated here. Can you help me please? Thanks. AL.
Hi Alain,
gw-round-up-1
is working for me locally… it’s hard to say what might be the issue on yours. I’d recommend creating a new form and trying it again with the bare minimum fields. Then re-introduce complexity until it stops working again. Let us know what you determine.I’ve struggled a lot with custom rounding (up) using gravity forms. Thank you so much for sharing this!
Very happy to help, Adal! 😄
Hello again David,
After further testing, I am actually experiencing the same issue reported by Wouter and JeanCarlos in the comments below. I am using the Gravity Forms Add-on for WooCommerce (and Subscriptions).
Here is the form: http://adaldesign.com/wp-content/uploads/gravityforms-export-2019-11-06.json
It seems that by the time your JS modifies the value, GF is already set on the previous value somehow…
I really appreciate your supporting this snippet and I hope that this will lead to improving it in a way that can benefit you as well!
Hi Adal, per our email exchange, this has been fixed. Thanks for the excellently detailed bug report. 🙂
Is it possible to round up in half increments eg. Can of paint at 2.5 litres round it up to 5 litres or 2.5 litres??
I’m not sure… did you try it? Let me know the result.
I did, it doesn’t work. I made a few changes to your script and got it to work, kind of a hack but it works for what i need it to do.
GWRounding.round function I added:
case ‘half’: interval = actionValue/2; base = Math.ceil( value / interval ); value = base * interval; break;
and changed return parseInt(value) to parseFloat(value)
D
Thanks for sharing, Damian!
Its possible to round up to different number, ex: 740 and after 1140 and after 1480 and after 1880….
740(+400)1140(+340)1480
thanks
Hi Nic, this is not currently supported.
What about rounding up to the nearest whole number. Does this apply? For example we get a calculation of 41.7 and we want it to round up to 42. Or if it spits out 13.1333, we still want it to round up to 14. Once again, not sure if this the “rounding” that applies. Thanks for your help.
Try
gw-round-1
to round to the nearest whole number andgw-round-up-1
to always round up to the nearest whole number.We’re doing some calculations and it spits out a negative number, which is fine, but we need any negative to become a 0. Is it possible to say any “negative number” round to a 0 (zero)?
Hi GenSki, try setting a minimum of zero:
gw-round-min-0
Hi, I’m a fan of this snippets, but this one has trouble, after put round-up-1, when pressing next page the rounded value return to its previous value, it doesn’t keep.
For example, 5.2 rounded to 6, when I press the next page the value 5.2 is the one that shows up in the summery and in the final submission. some can help me, please??
Hi Jeancarlos, can you send me a link to an export of your form?
Hello,
I have tried this script to round up to 50. I have a very long form, which I have split up in multiple pages. One page at a time everything seems to be fine, but once you move to a new page the number of items is updated once it gets over 1000.
It might have to do something with the decimal separator? We are using , als decimal separator and . als thousand separator. When I use no separate number field it goes wrong completely. See the video at https://1drv.ms/v/s!AmX03qnGqzAjj4RYmhWeA7flFQJGmQ Or http://www.belug.be/test2/
When I do use a separate number field: https://onedrive.live.com/?authkey=%21ACRodoa6uf4oK0c&cid=2330ABC6A9DEF465&id=2330ABC6A9DEF465%21246359&parId=2330ABC6A9DEF465%21167701&o=OneUp Or https://www.belug.be/test/
Enter a number of e.g. 3456. This gets rounded up to 3500 (which is correct). But when you move to the next page or submit, this number is incorrectly modified to 50 !
Can you help me out here?
Thanks a lot !
I’m using this in a calculation field with “gw-round-up-1” to round up decimals. It’s rounding down. What might I be doing wrong. If I remove the class, my formula is calculating correctly.
Hi Trevor, this has been fixed. Download the latest version of the snippet above. :)
David, this is really awesome!
I am experiencing one hiccup though – when the number field I intend to round is revealed (either by conditional logic or by proceeding to the next page), it is automatically populated by “choice_1_22_1” (form 1, field 22). This stays true on other fields as well (23, 34, etc).
When I change the field to a number, the rounding works as expected. If I hide the number input (again, either by conditional logic or page change) it is reset to “choice_1_22_1” again.
It’s really the only thing keeping me from being able to use this snippet. Do you have any thoughts? I’ve tried poking around in the code a bit, but my JS is weak.
Thanks!
Hi John, I’m not able to recreate this on my end. If you’re a Gravity Perks customer, we’ll be happy to provide additional support via the support form.