O'Reilly logo

VB.NET Language in a Nutshell, Second Edition by Steven Roman PhD, Paul Lomax, Ron Petrusha

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

CShort Function

Named Arguments

No

Syntax

CShort(expression)
expression (required; Numeric or String)

The range of expression is -32,768 to 32,767; fractions are rounded.

Return Value

expression cast as a Short

Description

Converts expression to a Short value; any fractional portion of expression is rounded.

Rules at a Glance

  • expression must evaluate to a numeric value; otherwise, a type-mismatch error is generated.

  • If the value of expression is outside the range of the Short data type, an overflow error is generated.

  • When the fractional part of expression is exactly .5, CShort always rounds it to the nearest even number. For example, .5 rounds to 0, and 1.5 rounds to 2.

Example

Dim iMyNumber as Short
If IsNumeric(sMyNumber) then
    iMyNumber = CShort(sMyNumber)
End If

Programming Tips and Gotchas

  • When converting a string representation of a number to a numeric, you should use the data type conversion functions — such as CShort — instead of Val, because the data type conversion functions take into account the system’s regional settings. In particular, CShort recognizes the thousands separator if it’s present in expression, whereas Val does not. For example, if expression is 1,234, CShort successfully converts it to the integer value 1234, while Val converts it to 1.

  • Use IsNumeric to test whether expression evaluates to a number before performing the conversion.

  • CShort differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. Also,

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required