Reputation: 29
We want to display dynamic value in a table using JavaScript in vb.net. we have define the variable as var rValue
.
The expression is rValue = parseFloat(594 * 0.1);
We are getting putput as 59.400000000000006
but we need the output as 59.4
please let us know how to do that .
P.S. We do not want to use tofixed()
as it will return the two decimal point for all the values which do not have decimal points.
Upvotes: 3
Views: 5452
Reputation: 1
easy arrow function:
const truncate = (number,decimals) =>
Math.trunc(number*Math.pow(10,decimals)) / Math.pow(10,decimals)
Upvotes: 0
Reputation: 2827
The problem arises from 0.1 not being able to be represented in binary. It actually has an infinite number of decimals, hence every arithmetic operation with this number results in the output being approximate.
You can either opt to use division by a float 10 instead:
var rValue = 594 / 10.0;
or, if this kind of truncation is a recurring issue, you can write a utility function:
/**
* @param {Number} value
* @param {Integer} precision
* @returns {Number}
*/
var truncateFloat = function(value, precision) {
// Ensure the multiplier is a float
var pMult = 1.0;
while (precision--) {
pMult *= 10;
}
// Multiply the value by the precision multiplier,
// convert it to int (discarding any pesky leftover decimals)
// and float-divide it by the same multiplier
return ((value * pMult) >> 0) / pMult;
}
Hope this helps a little! :)
Upvotes: 0
Reputation: 259
Like This ?
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim rValue As String = 56.40000000006
Dim charVal() As Char = rValue.ToCharArray()
Dim getVal As String = Nothing
'----------Change for decimal places---------
Dim decimalPlaces As Integer = 2
Dim decimalPlace As Integer = -1
Dim realValue As Double = 0
For Each Val As Char In charVal
If Char.IsDigit(Val) Then
getVal &= Val
Else
getVal &= "."
End If
If getVal.Contains(".") Then
decimalPlace += 1
End If
If decimalPlace = decimalPlaces Then
Exit For
End If
Next
MsgBox(realValue)
End Sub
Upvotes: -2
Reputation: 31839
Use the native toPrecision()
method:
<script>
var rValue = new Number(59.400000000000006 );
var n = rValue.toPrecision(3);
//n will be 59.4
</script>
Upvotes: 1
Reputation: 28558
try this:
var rValue = parseFloat(594 * .2);
alert(rValue.toFixed(2).replace(".00",""))
Upvotes: 1
Reputation: 1050
Use rValue = parseFloat(594 * 0.1).toFixed(2)
and if the decimal is .00 remove the decimal places.
e.g.
var num=rValue.split('.')[1];
if(num==='00')
{
rValue=rValue.split('.')[0];
}
Upvotes: 2