• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 489
  • Last Modified:

How to round and truncate long decimal strings in vb.net

I will have string data coming in, with 1, 2, or 3 digits preceding the decimal point, and 12 digits after the decimal point.  An example would be 12.918171615141.  I need to truncate everything past the 4th decimal digit, so that my example string would look like 12.9181.

Better yet would be if I could ROUND it properly, so that in this example I would end up with 12.9182.  But to do so, I assume I would have to move the string to a numeric variable and use a math function.  IF this is feasible, I need some sample code to handle this as well, i.e. how to properly get it into a numeric variable, then do the rounding, and get it back in to a string.  TIA
0
sasllc
Asked:
sasllc
3 Solutions
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
Please check double.parse and double.tryparse
0
 
Randy PooleCommented:
Dim yv as double
yv=12.918171615141
yv=Math.Round(yv, 3, MidpointRounding.AwayFromZero)

Open in new window

0
 
sasllcAuthor Commented:
In this example from Randy Poole, what is the right way to get my string into the numeric variable?  If my string is named strABC, do I simply say "yv=strABC"...or what is best?  

I really do need some sample showing me how to properly get the string into a numeric variable, then do the rounding, and get it back in to a string
0
 
Kyle AbrahamsSenior .Net DeveloperCommented:
Dim yv as Double 

if Double.TryParse(strABC, out yv) then
     'strABC a valid decimal.
     yv = Math.Round(yv, 3, MidpointRounding.AwayFromZero)
     strABC = yv.ToString()
else
    yv = nothing
   'string improperly formated, couldn't parse as a number.
end if


 

Open in new window

0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now