i'm trying to set an output value from 2 fields to 2 decimals.
i've tried doing this with: .toFixed(2) but it didn't work for me. I tried doing this:
calculate = function () {
var total = document.getElementById('totaal').value;
var btw = document.getElementById('percentage').value;
document.getElementById('btw').value = parseInt(total.toFixed(2)) * parseInt(btw.toFixed(2)) / 100;
}
If the field ends on a number with 2 decimals (for example: 3,45) it is working correctly.But if it ends with a 0, it does not show the 0.
I think this shoudn't be this mutch of a deal but i'm just trying for half a day now...
Thanks in advance!
When you use parseInt() you then get the numbers after the decimal points removed, try doing this :
document.getElementById('btw').value = (parseFloat(total) * parseFloat(btw) / 100).toFixed(2);
parseFloat converts the string (and it's necessary because input values are string) in the input to a float, then divide by 100 and call .toFixed(2) on the result.
You could convert a string to number by using an unary plus +.
document.getElementById('btw').value = (+total * +btw / 100).toFixed(2);
If you use parseInt, you loose precision, which you may have.
You can use parseFloat to achieve this
var total =65633;
var btw = 12;
console.log(parseFloat((total* btw)/100).toFixed(2))
Your issues is that you're running toFixed() on strings, and toFixed() only works on numbers.
You could however, do this:
document.getElementById('btw').value =
(parseInt(total) * parseInt(btw) / 100).toFixed(2)
This takes the two numbers and does all the math. It then converts it to a string with two trailing decimals
See my fiddle here: https://jsfiddle.net/6vtrjmax/
Make sure you are calling toFixed on the entire operation i.e. document.getElementById("btw").value = (parseInt(total) * parseInt(btw) / 100).toFixed(2);
Try running the snippet below:
calculate = function() {
var total = document.getElementById("total").value;
var btw = document.getElementById("percentage").value;
if (total && btw) {
document.getElementById("btw").value =
(parseInt(total) * parseInt(btw) / 100).toFixed(2);
}
};
<input onchange="calculate()" placeholder='total' type="decimal" id="total">
<input onchange="calculate()" placeholder='percentage' type="decimal" id="percentage">
<input type="decimal" placeholder='result' id="btw">
Related
How can I convert decimal number to 2 decimal place number?
Example: I want to connvert 4.995 to 4.99 but javascript is returning 5.00.
var price=4.995;
var rounded_price=price.toFixed(2);
console.log(rounded_price);
I wouldn't call it rounding but you can achieve it by:
function trim2Dec(n) {
return Math.floor(n * 100) / 100;
}
alert(trim2Dec(4.995));
You can use regex for this as the following:
alert("4.995".replace(/(\d+(\.\d{1,2})?)\d*/, "$1"))
This is Pretty simple check out this code
var price=4.995;
var price1=4.985;
var rounded_price=(Math.round(price*100)/100);
var rounded_price1=(Math.round(price1*100)/100);
console.log("price : "+rounded_price+" price1 : "+rounded_price1);
here at first i am multiplying the price and then i have divided it with 100..just as we do to find the percentage of any number.
I would format a number with 2 decimal places without rounding.
So I excluded the toFixed() function.
I have tried this way
a = 1,809999
b = 27,94989
a = Math.floor(a * 100) / 100; --> 1,8
b = Math.floor(b * 100) / 100; --> 27,94
OR
a = Number(a.toString().match(/^\d+(?:\.\d{0,2})?/)); --> 1,8
b = Number(b.toString().match(/^\d+(?:\.\d{0,2})?/)); --> 27,94
Unfortunately, the second decimal of a is zero, and this was deleted, how could I do to keep it and have a = 1.80?
Thank you
(Math.floor(a * 100) / 100).toFixed(2);
With toFixed(2) !
JSFIDDLE DEMO
You can try like this:
a= a.toString().slice(0, (a.indexOf("."))+3);
JSFIDDLE DEMO
Rounding a number is about changing it's value, and should be done with math operations (Math.floor, Math.ceil, Math.round, ...).
Formatting number, is about how do numbers get displayed to a human user (like Date formatting).
Javascript does not comes with acceptable native tool to do number formatting.
You can always play with rounding to make javascript print a number the way you want, but you will end up writing a lot of (possibly buggy) code.
I would recommend using a library to format your numbers
http://numeraljs.com/
numeral(number).format('0.00');
only need to use toFixed() and pass number like 2 then it show after . two decimal like bello
a = 1,809999
b = 27,94989
a = Math.floor(a * 100) / 100;
b = Math.floor(b * 100) / 100;
$(".testa").text(a.toFixed(2)); //see here.
$(".testb").text(b.toFixed(2)); //see here.
Html :
<div class="testa"></div>
<br>
<div class="testb"></div>
i hope this will help you. and also see this jsfiddle link http://jsfiddle.net/RGerb/394/
myFunction(value: number){
let x = value + '';
var a = x.lastIndexOf('.')>=0?parseFloat(x.substr(0,x.lastIndexOf('.')+(3))):value;
var am = a.toFixed(2)
console.log("Output: " + am);
return am;
}
<button (click)="myFunction(656565.9668985)">My Function</button>
Output: 656565.96
I have this :
i=4.568;
document.write(i.toFixed(2));
output :
4.57
But i don't want to round the last number to 7 , what can i do?
Use simple math instead;
document.write(Math.floor(i * 100) / 100);
(jsFiddle)
You can stick it in your own function for reuse;
function myToFixed(i, digits) {
var pow = Math.pow(10, digits);
return Math.floor(i * pow) / pow;
}
document.write(myToFixed(i, 2));
(jsFiddle)
Just cut the longer string:
i.toFixed(3).replace(/\.(\d\d)\d?$/, '.$1')
A slightly convoluted approach:
var i=4.568,
iToString = i + '';
i = parseFloat(iToString.match(/\d+\.\d{2}/));
console.log(i);
This effectively takes the variable i and converts it to a string, and then uses a regex to match the numbers before the decimal point and the two following that decimal point, using parseFloat() to then convert it back to a number.
References:
match()
parseFloat().
Regular Expressions.
I need to round off the decimal value to decimal places using javascript.
Ex,:
16.181 to 16.18
16.184 to 16.18
16.185 to 16.19
16.187 to 16.19
I have found some answers, but most of them do not round off 16.185 to 16.19..
(Math.round((16.185*Math.pow(10,2)).toFixed(1))/Math.pow(10,2)).toFixed(2);
If your value is, for example 16.199 normal round will return 16.2... but with this method youll get last 0 too, so you see 16.20! But keep in mind that the value will returned as string. If you want to use it for further operations, you have to parsefloat it :)
And now as function:
function trueRound(value, digits){
return (Math.round((value*Math.pow(10,digits)).toFixed(digits-1))/Math.pow(10,digits)).toFixed(digits);
}
Thanks #ayk for your answer, I modified your function into this :
function trueRound(value, digits){
return ((Math.round((value*Math.pow(10,digits)).toFixed(digits-1))/Math.pow(10,digits)).toFixed(digits)) * 1;
}
just add " *1 "
because with yours, as you wrote, 16.2 becomes 16.20
and I don't need the zero in the back.
Use-
Decimal ds=new Decimal(##.##);
String value=ds.format(inputnumber);
This will work perfectly in my case ,hope it will work 100%
The code you are using for rounding off is correct. But to get the desired result please remove the .toFixed(numOfDec) from the code.
The function:
function formatNumber(myNum, numOfDec) {
var decimal = 1
for (i = 1; i <= numOfDec; i++)
decimal = decimal * 10 //The value of decimal determines the number of decimals to be rounded off with (.5) up rule
var myFormattedNum = Math.round(myNum * decimal) / decimal
return (myFormattedNum)
}
Hope it helps you in some way :)
function formatNumber(myNum, numOfDec) {
var dec = Math.pow(10, numOfDec);
return Math.round(myNum * dec + 0.1) / dec;
}
parseFloat(myNum.toFixed(numOfDec))
[EDIT]
This code does not work for a value like 18.185, as 18.185 * Math.pow(10,2) is being evaluated to 1818.4999999999997
Math.round(<value> * Math.pow(10,<no_of_decimal_places>)) / Math.pow(10,<no_of_decimal_places>) ;
Example:
1234.5678 --> 2 decimal places --> 1234.57
Math.round(1234.5678 * Math.pow(10,2)) / Math.pow(10,2) ;
You COULD try a simpler function...
function roundOffTo(number, place) {
return Math.round(number * place) / place;
}
How does it work?
The place can be 10, 100, 1000, 10000, and so on. The reverse will be 0.1, 0.01, 0.001, and so on. Let's say your number is 16.185, and your place is 100. The first thing it'll do is to multiply the number by the place, which is 1618.5. Rounding it off by Math.round will result in 1619. Dividing by the place gives us 16.19. There.
By the way, no need to worry about the .5 problem today, it's kinda fixed. But just in case it isn't, change Math.round(number * place) to Math.round(number * place + 0.1).
I wanted to display a number to 2 decimal places.
I thought I could use toPrecision(2) in JavaScript .
However, if the number is 0.05, I get 0.0500. I'd rather it stay the same.
See it on JSbin.
What is the best way to do this?
I can think of coding a few solutions, but I'd imagine (I hope) something like this is built in?
float_num.toFixed(2);
Note:toFixed() will round or pad with zeros if necessary to meet the specified length.
You could do it with the toFixed function, but it's buggy in IE. If you want a reliable solution, look at my answer here.
number.parseFloat(2) works but it returns a string.
If you'd like to preserve it as a number type you can use:
Math.round(number * 100) / 100
Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:
var num = response_from_a_function_or_something();
var fixedNum = parseFloat(num).toFixed( 2 );
with toFixed you can set length of decimal points like this:
let number = 6.1234
number.toFixed(2) // '6.12'
but toFixed returns a string and also if number doesn't have decimal point at all it will add redundant zeros.
let number = 6
number.toFixed(2) // '6.00'
to avoid this you have to convert the result to a number. you can do this with these two methods:
let number1 = 6
let number2 = 6.1234
// method 1
parseFloat(number1.toFixed(2)) // 6
parseFloat(number2.toFixed(2)) // 6.12
// method 2
+number1.toFixed(2) // 6
+number2.toFixed(2) // 6.12
Try toFixed instead of toPrecision.
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // return 1.01
round(1.004, 2); // return 1 instead of 1.00
The answer is following this link: http://www.jacklmoore.com/notes/rounding-in-javascript/
I used this way if you need 2 digits and not string type.
const exFloat = 3.14159265359;
console.log(parseFloat(exFloat.toFixed(2)));
You could try mixing Number() and toFixed().
Have your target number converted to a nice string with X digits then convert the formated string to a number.
Number( (myVar).toFixed(2) )
See example below:
var myNumber = 5.01;
var multiplier = 5;
$('#actionButton').on('click', function() {
$('#message').text( myNumber * multiplier );
});
$('#actionButton2').on('click', function() {
$('#message').text( Number( (myNumber * multiplier).toFixed(2) ) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button id="actionButton">Weird numbers</button>
<button id="actionButton2">Nice numbers</button>
<div id="message"></div>
The toFixed() method formats a number using fixed-point notation.
and here is the syntax
numObj.toFixed([digits])
digits argument is optional and by default is 0. And the return type is string not number. But you can convert it to number using
numObj.toFixed([digits]) * 1
It also can throws exceptions like TypeError, RangeError
Here is the full detail and compatibility in the browser.
let a = 0.0500
a.toFixed(2);
//output
0.05
There's also the Intl API to format decimals according to your locale value. This is important specially if the decimal separator isn't a dot "." but a comma "," instead, like it is the case in Germany.
Intl.NumberFormat('de-DE').formatToParts(0.05).reduce((acc, {value}) => acc += value, '');
Note that this will round to a maximum of 3 decimal places, just like the round() function suggested above in the default case. If you want to customize that behavior to specify the number of decimal places, there're options for minimum and maximum fraction digits:
Intl.NumberFormat('de-DE', {minimumFractionDigits: 3}).formatToParts(0.05)
float_num = parseFloat(float_num.toFixed(2))
I have made this function. It works fine but returns string.
function show_float_val(val,upto = 2){
var val = parseFloat(val);
return val.toFixed(upto);
}