2012-07-05 8 views
8

テキストボックスに表示するために、double値の小数点以下の桁数を切り捨てる必要があります。どのようにvbaでこれを達成するでしょうか?上記のあなたに1.57を与える:VBAでdoubleを切り捨てる

答えて

7

あなたは、小数点以下2桁

Dval = 1.56789 

Debug.Print Round(dVal,2) 

Debug.Print Format(dVal,"0.00") 

を示すために、例えば

VBA

FORMATため ROUNDを使用することができます。ですから、 1.56を探しているなら、あなたは、文字列でDVALを格納し、あなたが ラウンドに値をしたい場合は、あなたがラウンド関数を使用します(ただし、そのVBAの認識することができ、この

Dim strVal As String 

dVal = 1.56789 
strVal = dVal 

If InStr(1, strVal, ".") Then 
    Debug.Print Split(strVal, ".")(0) & "." & Left(Split(strVal, ".")(1), 2) 
Else 
    Debug.Print dVal 
End If 
6

行うことができますラウンド関数はバンカーの丸めを使用します(ラウンド・ツー・イーブン、ラウンド・トゥ・イーブン、ラウンド・トゥ・イヤー、ラウンド・トゥ・イヤー)。

あなたは丸めずに切り捨てに値をしたい場合は、受け入れ答えのように文字列を使用する必要はありません - ちょうど数学を使用します。

Dim lDecimalPlaces As Long: lDecimalPlaces = 2 
Dim dblValue As Double: dblValue = 2.345 

Dim lScale = 10^lDecimalPlaces 
Dim dblTruncated As Double: dblTruncated = Fix(dblValue * lScale)/lScale 

これは、「2.34」を生み出します。

+0

私の場合、修正機能は非常に役に立ちました。 – carlossierra

+1

私はバンカーの丸めを忘れていました。驚くべき "ただの数学を使う"ジャブにもかかわらず+1。あなたが丸めを気にしない場合、Format()はジョブのツールであり、Fix()(またはInt())(Fix()と同等です)より簡単です。正の数の場合)。ただし、バンカーの丸めによってユーザーの疑問が生じ、より複雑な変換が必要な場合があります。 – GlennFromIowa

4

Int()関数を使用できます。 Debug.print Int(1.99543)

またはそれ以上:

Public Function Trunc(ByVal value As Double, ByVal num As Integer) As Double 
    Trunc = Int(value * (10^num))/(10^num) 
End Function 

だから、Trunc(1.99543, 4) ==>result: 1.9954

0

とても楽しい物語を使用することができます。私は素早くVB変換機能を使いこなしていました。私は、ダブルを整数に切り捨てたいだけです。

value = Int(83.768) 
value == 83 

素晴らしいですが、実際にはVBで何かが働いていました。

おっと、私はそれがちょうど起こっええ...それは負の数

value = Int(-83.768) 
value == -84 

では動作しません忘れてしまいました。 VBはバンカーの丸めを使用します。

Public Function Trunc(ByVal value As Double) As Integer 
    ' Truncate by calling Int on the Absolute value then multiply by the sign of the value. 
    ' Int cannot truncate doubles that are negative 
    Trunc = (Abs(value)/value) * Int(Abs(value)) 
End Function 

あなたが特定の小数点以下の桁数が必要な場合Makahは値の周りのAbsとだけやったので、Intが適切に切り捨てることができます。

Public Function Trunc2(ByVal value As Double, Optional ByVal num As Integer = 1) As Double 
    ' Truncate by calling Int on the Absolute value then multiply by the sign of the value. 
    ' Int cannot truncate doubles that are negative 
    Dim sign As Integer 
    sign = Abs(value)/value 
    Trunc2 = sign * (Int(Abs(value) * (10^num))/(10^num)) 
End Function 
関連する問題