Imports System.Runtime.CompilerServices
Module _Extensions
<Extension()>
Public Function ToDouble(ByVal input As String, ByVal d As Integer)
ToDouble = Convert.ToDouble(input).ToDouble(d)
End Function
<Extension()>
Public Function ToDouble(ByVal input As Double, ByVal d As Integer)
ToDouble = input.ToString("N" & d)
End Function
End Module
เวลาเรียกใช้ก็
Code (VB.NET)
Text = "0.1264".ToDouble(3)
Text = (22 / 7).ToDouble(5)
Imports System.Runtime.CompilerServices
Module _Extensions
<Extension()>
Public Function ToDouble(ByVal input As String, ByVal d As Integer)
ToDouble = Convert.ToDouble(input).ToDouble(d)
End Function
<Extension()>
Public Function ToDouble(ByVal input As Double, ByVal d As Integer)
ToDouble = input.ToString("N" & d)
End Function
End Module
คือว่าผมอยากจะเปลี่ยน string หรือ Double ใดๆก็ตามให้มีจุดทศนิยมตามที่เราต้องการ
โดยผมสร้าง Extension Methods ขึ้นมาชื่อ ToDouble
จะเห็นว่ามันมีทั้ง
Public Function ToDouble(ByVal input As String, ByVal d As Integer)
และ
Public Function ToDouble(ByVal input As Double, ByVal d As Integer)
Imports System.Runtime.CompilerServices
Module _Extensions
<Extension()>
Public Function ToDouble(ByVal input As String, Optional d As Integer = 2) As Double
ToDouble = Convert.ToDouble(input).ToDouble(d)
End Function
<Extension()>
Public Function ToDouble(ByVal input As Double, Optional d As Integer = 2) As Double
ToDouble = Convert.ToDouble(input.ToString("N" & d))
End Function
<Extension()>
Public Function ToDouble(ByVal input As Double, Optional format As String = "N2") As Double
ToDouble = Convert.ToDouble(input.ToString(format))
End Function
<Extension()>
Public Function ToDouble(ByVal input As Object, Optional format As String = "N2") As Double
ToDouble = Convert.ToDouble(input).ToDouble(format)
End Function
<Extension()>
Public Function ToDouble(ByVal input As Object, Optional d As Integer = 2) As Double
ToDouble = Convert.ToDouble(input).ToDouble(d)
End Function
End Module
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Text = (22 / 7).ToDouble(1).ToString()
End Sub
End Class
Module _Extensions
<Extension()>
Public Function ToDouble(ByVal input As String, ByVal d As Integer)
ToDouble = Convert.ToDouble(input).ToDouble(d)
End Function
<Extension()>
Public Function ToDouble(ByVal input As Double, ByVal d As Integer)
ToDouble = input.ToString("N" & d)
End Function
End Module