Number Truncation

I’ve been experimenting in Hopscotch to find a way to truncate numbers, for example instead of 41,365 being displayed, 41.36K would be displayed. It is an important aspect of games, and I’ve been wondering if there is a way that this can be achieved using a shorter method. Currently I’m using a system where an ‘if else’ block is used to detect if a number is over 1000, then it converts into a smaller number and adds a K. This is the same for millions, billions, trillions, etc.
Just wondering if there is a method that doesn’t require as much blocks that I use.

8 Likes

Here is a project that can help

It’s a bit complicated lol

https://c.gethopscotch.com/p/135urxnvtr

5 Likes

this helped alot ty :)))

3 Likes

Here’s a pretty simple implementation as a custom block. In the actual project I forgot to add support for numbers < 1000, but that’s an easy fix

The code to support smaller/negative numbers would basically be this:
The only changes to the project are adding a check if else to support numbers that don’t change and using the length of the absolute value of the number to support negative numbers.

custom_block format(number: 3720, decimal_digits: 2):
	check_if_else(absolute_value(number) < 1000):
		# Numbers less than 1000 and greater than -1000 don't change
		Self.↩️formatted_number = number
	else:
		# The letters to put after each triplet of zeroes (k for thousand, m for million, etc.)
		# Only supports 1-letter abbreviations at the moment
		abbreviation_letters = "kmbt"
		number_of_zero_triplets = min(length(absolute_value(abbreviation_letters)), floor(length(number) / 3))
		letter_part = character_at_index(in: abbreviation_letters, at: number_of_zero_triplets - 1)
		number_part = number / 10 ^ multiply(3, *: number_of_zero_triplets)
		# Round the number part
		number_part = round(number_part * 10 ^ decimal_digits) / 10 ^ decimal_digits
		Self.↩️formatted_number = join(number_part, with: letter_part)

Let me know if there’s any part of this that doesn’t make sense.

4 Likes

This works very well! :)) I’ll try to edit the code to add more abbreviation letters and see if it works properly.

UPD: I simplified the code and got it to work with 2-letter abbreviations!

5 Likes

IMG_5282

This is def a bug @Petrichor

2 Likes

Yeah, that’s fixed in the text I provided but in the actual project it only correctly handles numbers ≥ 1000

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.