-2

I want my program to enter a decimal that will output in 4 decimal places by not rounding the inputed number

input: 0.6363636364

output: 0.6363

hotchongas
  • 35
  • 3
  • 1
    Possible duplicate of [Truncate Decimal number not Round Off](http://stackoverflow.com/questions/329957/truncate-decimal-number-not-round-off) – Naruto Apr 17 '16 at 11:56
  • SALAMAT!!!(thank you) – hotchongas Apr 17 '16 at 12:15
  • @Naruto Unfortunately, all of the suggestions on that `duplicate` suffer from possible overflow. The best answer to truncating to a specified number of digits is Tim Lloyd's answer to [Truncate Two decimal places without rounding](http://stackoverflow.com/a/14629365/3992902) – MrGadget Apr 17 '16 at 14:18

1 Answers1

0

For completeness, since the OP requested a VB solution, here's the Decimal extension based on Tim Lloyd's answer to Truncate Two decimal places without rounding:

Module MyExtensions
    <System.Runtime.CompilerServices.Extension>
    Public Function TruncateDecimal(d As Decimal, decimals As Integer) As Decimal
        Select Case True
            Case decimals < 0
                Throw New ArgumentOutOfRangeException("decimals", "Value must be in range 0-28.")
            Case decimals > 28
                Throw New ArgumentOutOfRangeException("decimals", "Value must be in range 0-28.")
            Case decimals = 0
                Return Math.Truncate(d)
            Case Else
                Dim IntegerPart As Decimal = Math.Truncate(d)
                Dim ScalingFactor As Decimal = d - IntegerPart
                Dim Multiplier As Decimal = Math.Pow(10, decimals)

                ScalingFactor = Math.Truncate(ScalingFactor * Multiplier) / Multiplier

                Return IntegerPart + ScalingFactor
        End Select
    End Function
End Module

Usage:

Dim Value As Decimal = 0.6363636364
Value = Value.TruncateDecimal(4)
Community
  • 1
  • 1
MrGadget
  • 1,258
  • 1
  • 10
  • 19