65.9K
CodeProject 正在变化。 阅读更多。
Home

数字转换(1 到 “1st” 等)

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.80/5 (5投票s)

2003年3月20日

viewsIcon

81813

一篇关于数字转换的文章,将基本数字转换为带有后缀的数字。(例如,将 1 转换为 “1st”)

引言

这个小函数非常简单,但非常实用。我多次遇到这个问题,通常尽量避免它,但最终我有一个项目*坚持*要求我以这种方式格式化一些数字,所以就这样了。

使用代码

这是一个基本的函数调用。将任何大于 0 的数字发送给它,它将返回带有 “st”、“nd”、“rd” 或 “th” 后缀的格式化数字。发送空字符串将导致显示错误消息。

dim iTestNumber 'number to be passed to function

dim sNewNumber  'string returned from function

dim x           'loop incriment


' this function will format a number with it's given suffix. (1st, 2nd, 3rd)

Function BuildNumber(iNum)
dim sNewNum
sNewNum = iNum if right(iNum, 2) = "11" or right(iNum, 2) = "12" or _ right(iNum, 2) = "13" then sNewNum = sNewNum & "th" else iNum = right(iNum, 1) select case iNum case "1" sNewNum = sNewNum & "st" case "2" sNewNum = sNewNum & "nd" case "3" sNewNum = sNewNum & "rd" case "" sNewNum = "error" case else sNewNum = sNewNum & "th" end select end if if sNewNum = "error" then response.write "There was an error with the date passed to the "
response.write "function. The date must be an integer greater "
response.write "than 0 and not equal to blank. Please use the "
response.write "back button to fix the problem or contact customer "
response.write "support. Thank you." response.End end if buildnumber = sNewNum end function for x = 1 to 100 iTestNumber = x sNewNumber = BuildNumber(iTestNumber) response.write("This is the value sent to the function: "
response.write iTestNumber & "<br>") response.write("This is the value returned from the function: "
response.write "sNewNumber & "<br><HR>") next response.end

关注点

注意一些小陷阱,例如 “11”、“12” 和 “13” 都以 “th” 结尾,而不是 “st”、“nd” 和 “rd”。我想这些是唯一的例外情况。它应该适用于负数,但我不知道为什么要这样做。但这取决于你。

© . All rights reserved.