It is currently March 28th, 2024, 3:18 pm

Number formatting...

Discuss the use of Lua in Script measures.
Post Reply
User avatar
jsmorley
Developer
Posts: 22628
Joined: April 19th, 2009, 11:02 pm
Location: Fort Hunt, Virginia, USA

Number formatting...

Post by jsmorley »

Here are a couple of functions to do some number formatting in Lua.

1) Add the "ordinal" postfix (st, nd, rd, th) to a number.

Code: Select all

function OrdinalPostfix(number)

	strNum = tostring(number)
	last_digit = string.sub(strNum, -1, 1)
	if string.len(strNum) > 1 then
		next_to_last = string.sub(strNum, -2, 1)
	else
		next_to_last = ""
	end
	
	if last_digit == "1" then
		if next_to_last == "1" then
			OrdinalEnd = "th"
		else
			OrdinalEnd = "st"
		end
	elseif last_digit == "2" then
		if next_to_last == "1" then
			OrdinalEnd = "th"
		else
			OrdinalEnd = "nd"
		end
	elseif last_digit == "3" then		
		if next_to_last == "1" then
			OrdinalEnd = "th"
		else
			OrdinalEnd = "rd"
		end
	else
		OrdinalEnd = "th"
	end
	
	return OrdinalEnd
		
end -->OrdinalPostfix
2) Add commas to numbers over 999.

Code: Select all

function AddCommas(number)

	local formatted = tostring(number)

	while true do
		formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
		if (k == 0) then
			break
		end
	end

	return formatted
	
end -->AddCommas
Now let's put it all together in a skin:

Code: Select all

[Rainmeter]
Update=1000

[MeasureRandom]
Measure=Calc
Formula=RANDOM
LowBound=0
HighBound=10000
UpdateRandom=1
UpdateDivider=10

[MeasureLua]
Measure=Script
ScriptFile=Ordinal.lua
UpdateDivider=10
DoCommas=1
DoOrdinal=1

[MeterString]
Meter=String
MeasureName=MeasureRandom
MeasureName2=MeasureLua
FontSize=13
FontColor=255,255,255,255
SolidColor=0,0,0,1
StringStyle=Bold
AntiAlias=1
Text=%1 : %2
LeftMouseUpAction=!Refresh #CURRENTCONFIG#
Ordinal_1.0.rmskin
(1.42 KiB) Downloaded 167 times
7-10-2012 9-33-09 AM.jpg
Post Reply