VB Truncate function

Larry Brister
Larry Brister used Ask the Experts™
on
I need a function in VB that I feed in a decimal number and a "place" integer and it truncates the string and drops everything to the right of my "place integet

Example GetMyDecimalPlace(0.124599999,4)

Wouuld return 0.1245
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
You could use format to set the number of spaces after the decimal.  

Format(0.124599999, "0.0000")
would return 0.1245
Commented:
Try this for 4 decimal places (if you need more or less just change the 4 to the number of decimals you need):
FormatNumber(1.23456,4)
Kyle AbrahamsSenior .Net Developer

Commented:
check my loop for the number of times the decimal moves, but the rest works.

function GetMyDecimalPlace(num as Double, int as numPlaces)

dim pow as integer = 1


for i as integer = 0 to numPlaces
  pow = pow * 10
next

'move decimal place
num = num * pow

'clear rest
truncate(num)

'move decimal back
num = num / pow

return num

end function

Paul MacDonaldDirector, Information Systems

Commented:
VB.Net already has a command to do this:
FormatNumber(number, number of digits after the decimal)
So:
Dim x As Decimal = FormatNumber(0.124599999, 4)
returns what you want
Larry Bristersr. Developer

Author

Commented:
Excellnet...thanks

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial