Skip to content

Commit

Permalink
Another rounding fix
Browse files Browse the repository at this point in the history
  • Loading branch information
skontar committed Oct 14, 2024
1 parent e5c64e0 commit 7554221
Show file tree
Hide file tree
Showing 6 changed files with 1,954 additions and 1,943 deletions.
2 changes: 1 addition & 1 deletion cvss/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@
from .exceptions import CVSS2Error, CVSS3Error, CVSS4Error, CVSSError
from .interactive import ask_interactively

__version__ = "3.2"
__version__ = "3.3"
17 changes: 14 additions & 3 deletions cvss/cvss4.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,19 @@
from .exceptions import CVSS4MalformedError, CVSS4MandatoryError


def round_away_from_zero(x):
return float(D(x * 10).quantize(D("1"), rounding=ROUND_HALF_UP) / 10)
def final_rounding(x):
"""
Round to one decimal place. Use Decimal because Python float rounding defaults to
"round half to even". We actually want "round half away from zero" aka "round half up" for
positive numbers.
Make sure that values like the following are correctly rounded despite floating point
inaccuracies:
8.6 - 7.15 = 1.4499999999999993 (float) => 1.5
"""
pre_rounded = D(x).quantize(D("0.00001"), rounding=ROUND_HALF_UP)
return float(D(pre_rounded).quantize(D("0.1"), rounding=ROUND_HALF_UP))


class CVSS4(object):
Expand Down Expand Up @@ -547,7 +558,7 @@ def compute_base_score(self):
value = max(0.0, value)
value = min(10.0, value)

self.base_score = round_away_from_zero(value)
self.base_score = final_rounding(value)

def clean_vector(self, output_prefix=True):
"""
Expand Down
Loading

0 comments on commit 7554221

Please sign in to comment.