diff --git a/contrib/pg_trgm/expected/pg_trgm.out b/contrib/pg_trgm/expected/pg_trgm.out
index 81d0ca80b206394799de4a3f1a9bdaba0f124364..ea4d5fab061e2a56bd2794f02a014fdb54d6677c 100644
--- a/contrib/pg_trgm/expected/pg_trgm.out
+++ b/contrib/pg_trgm/expected/pg_trgm.out
@@ -53,6 +53,12 @@ select similarity('wow',' WOW ');
           1
 (1 row)
 
+select similarity('---', '####---');
+ similarity 
+------------
+          0
+(1 row)
+
 CREATE TABLE test_trgm(t text);
 \copy test_trgm from 'data/trgm.data
 select t,similarity(t,'qwertyu0988') as sml from test_trgm where t % 'qwertyu0988' order by sml desc, t;
diff --git a/contrib/pg_trgm/sql/pg_trgm.sql b/contrib/pg_trgm/sql/pg_trgm.sql
index 81ab1e79b17df0c5855b10e01298ab765e95d94d..b235ca7357775b83e49a0c852047f56413e82fd3 100644
--- a/contrib/pg_trgm/sql/pg_trgm.sql
+++ b/contrib/pg_trgm/sql/pg_trgm.sql
@@ -11,6 +11,8 @@ select show_trgm('a b C0*%^');
 select similarity('wow','WOWa ');
 select similarity('wow',' WOW ');
 
+select similarity('---', '####---');
+
 CREATE TABLE test_trgm(t text);
 
 \copy test_trgm from 'data/trgm.data
diff --git a/contrib/pg_trgm/trgm_op.c b/contrib/pg_trgm/trgm_op.c
index 87dffd1dd2c9b773c91c1243e96f6483735e601d..9638dbdb701dd46ce5c8960b1428b54cac9e961d 100644
--- a/contrib/pg_trgm/trgm_op.c
+++ b/contrib/pg_trgm/trgm_op.c
@@ -553,6 +553,10 @@ cnt_sml(TRGM *trg1, TRGM *trg2)
 	len1 = ARRNELEM(trg1);
 	len2 = ARRNELEM(trg2);
 
+	/* explicit test is needed to avoid 0/0 division when both lengths are 0 */
+	if (len1 <= 0 || len2 <= 0)
+		return (float4) 0.0;
+
 	while (ptr1 - GETARR(trg1) < len1 && ptr2 - GETARR(trg2) < len2)
 	{
 		int			res = CMPTRGM(ptr1, ptr2);
@@ -570,9 +574,9 @@ cnt_sml(TRGM *trg1, TRGM *trg2)
 	}
 
 #ifdef DIVUNION
-	return ((((float4) count) / ((float4) (len1 + len2 - count))));
+	return ((float4) count) / ((float4) (len1 + len2 - count));
 #else
-	return (((float) count) / ((float) ((len1 > len2) ? len1 : len2)));
+	return ((float4) count) / ((float4) ((len1 > len2) ? len1 : len2));
 #endif
 
 }