PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 11, 2022

[FIXED] How to setup rounding halves to down in f-string format?

 August 11, 2022     decimal, python, rounding     No comments   

Issue

I'm trying to change the behaviour of my code in this way, expected behaviour:

2249 -> 2.2
2250 -> 2.2
2251 -> 2.3
2349 -> 2.3
2350 -> 2.3
2351 -> 2.4

But f'{num:.3g}' rounds it differently:

from decimal import *
def format_number(num):
  getcontext().prec = 1
  getcontext().rounding = ROUND_HALF_DOWN

  num = Decimal(num)
  print(num)
  num = float(f'{num:.3g}')
  print(num)
  magnitude = 0
  while abs(num) >= 1000:
    magnitude += 1
    num /= 1000.
  num = round(num * 10.) / 10.
  return f"{f'{num:f}'.rstrip('0').rstrip('.')}{['', 'k', 'M', 'B', 'T'][magnitude]}"

format_number(2349)
2349
2350.0
'2.4k'

How can I change it and keep "thouthands to letter" replacement?


Solution

You can change the precision width of your format of num as 2 instead of 3. that will round the digits after the precision width. since you only seem to want precision of the first two digits it will round these using the remaining digits.

from decimal import *


def format_number(num):
    getcontext().prec = 1
    getcontext().rounding = ROUND_HALF_DOWN

    num = Decimal(num)
    #print(num)
    num = float(f'{num:.2g}')
    #print(num)
    magnitude = 0
    while abs(num) >= 1000:
        magnitude += 1
        num /= 1000.
    num = round(num * 10.) / 10.
    return f"{f'{num:f}'.rstrip('0').rstrip('.')}{['', 'k', 'M', 'B', 'T'][magnitude]}"


nums = [2249, 2250, 2251, 2349, 2350, 2351, 2349345, 2351345]
for num in nums:
    print(f"{num} -> {format_number(num)}")

OUTPUT

2249 -> 2.2k
2250 -> 2.2k
2251 -> 2.3k
2349 -> 2.3k
2350 -> 2.3k
2351 -> 2.4k
2349345 -> 2.3M
2351345 -> 2.4M


Answered By - Chris Doyle
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing