Python Add Comma Into Number String

前端 未结 9 1066
陌清茗
陌清茗 2020-11-29 02:37

Using Python v2, I have a value running through my program that puts out a number rounded to 2 decimal places at the end:

like this:

print (\"Total          


        
9条回答
  •  青春惊慌失措
    2020-11-29 03:22

    The above answers are so much nicer than the code I was using in my (not-homework) project:

    def commaize(number):
        text = str(number)
        parts = text.split(".")
        ret = ""
        if len(parts) > 1:
            ret = "."
            ret += parts[1] # Apparently commas aren't used to the right of the decimal point
        # The -1 offsets to len() and 0 are because len() is 1 based but text[] is 0 based
        for i in range(len(parts[0]) - 1,-1,-1):
            # We can't just check (i % 3) because we're counting from right to left
            #  and i is counting from left to right. We can overcome this by checking
            #  len() - i, although it needs to be adjusted for the off-by-one with a -1
            # We also make sure we aren't at the far-right (len() - 1) so we don't end
            #  with a comma
            if (len(parts[0]) - i - 1) % 3 == 0 and i != len(parts[0]) - 1:
                ret = "," + ret
            ret = parts[0][i] + ret
        return ret
    

提交回复
热议问题