Reputation: 19843
I want to format my numbers and I want these results.
I have tried .toFixed(2)
but it didn’t yield the expected results.
Input Result
50.000 => 50
50.900 => 50.9
50.940 => 50.94
50.941 => 50.94
Something like 0.##
as formatting but in JavaScript.
Upvotes: 0
Views: 72
Reputation: 1039
change you number to string. After some string operations you can get correct result
<script language="Javascript">
var data = 50.947;
var res = data.toString().substring(0, data.toString().indexOf('.') + 3);
alert(res);
</script>
Upvotes: 0
Reputation: 8206
function decimalFunction() {
console.log('click');
var myvalue = document.getElementById('myInput').value;
var decimal = Math.round(myvalue * 100) / 100
document.getElementById('result').innerHTML = decimal;
}
<input id="myInput" type="text"/>
<button onclick="decimalFunction()">Submit</button>
<div id="result"></div>
Math.round(inputNumber * 100) / 100
Input: 50.000, 50.900, 50.940, 50.941
Output: 50, 50.9, 50.94, 50.94
Upvotes: 1
Reputation: 11812
You should be able to use
parseFloat(num.toFixed(2));
to
Upvotes: 1