JS - Format number with 2 decimal not rounded - javascript

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

Related

How can I display a variable in an exponential format with 2 decimals in javascript?

I am trying to get the right format for my operations, I want an exponential but I would like to limit the number of displayed decimals to only 2, like for example 1.13E+2 how can I do this work? Thanks in advance
row.querySelector(".one").value = (C1 * fuel).toExponential();
row.querySelector(".two").value = (C2 * fuel).toExponential();
row.querySelector(".three").value = (C3 * fuel).toExponential();
You can use toFixed, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
row.querySelector(".one").value = Number.parseFloat((C1 * fuel).toExponential(2));

Javascript end to 2 decimals not working

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">

Rounding up to two decimal place in javascript eg 4.9995 to 4.99 in mathematical way in js

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.

round off decimal using javascript

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).

How can I round a number in JavaScript? .toFixed() returns a string?

Am I missing something here?
var someNumber = 123.456;
someNumber = someNumber.toFixed(2);
alert(typeof(someNumber));
//alerts string
Why does .toFixed() return a string?
I want to round the number to 2 decimal digits.
Number.prototype.toFixed is a function designed to format a number before printing it out. It's from the family of toString, toExponential and toPrecision.
To round a number, you would do this:
someNumber = 42.008;
someNumber = Math.round( someNumber * 1e2 ) / 1e2;
someNumber === 42.01;
// if you need 3 digits, replace 1e2 with 1e3 etc.
// or just copypaste this function to your code:
function toFixedNumber(num, digits, base){
var pow = Math.pow(base||10, digits);
return Math.round(num*pow) / pow;
}
.
Or if you want a “native-like” function, you can extend the prototype:
Number.prototype.toFixedNumber = function(digits, base){
var pow = Math.pow(base||10, digits);
return Math.round(this*pow) / pow;
}
someNumber = 42.008;
someNumber = someNumber.toFixedNumber(2);
someNumber === 42.01;
//or even hexadecimal
someNumber = 0xAF309/256; //which is af3.09
someNumber = someNumber.toFixedNumber(1, 16);
someNumber.toString(16) === "af3.1";
However, bear in mind that polluting the prototype is considered bad when you're writing a module, as modules shouldn't have any side effects. So, for a module, use the first function.
I've solved this problem by changing this:
someNumber = someNumber.toFixed(2)
...to this:
someNumber = +someNumber.toFixed(2);
However this will convert the number to a string and parse it again, which will have a significant impact on performance. If you care about performance or type safety, check the the other answers as well.
It returns a string because 0.1, and powers thereof (which are used to display decimal fractions), are not representable (at least not with full accuracy) in binary floating-point systems.
For example, 0.1 is really 0.1000000000000000055511151231257827021181583404541015625, and 0.01 is really 0.01000000000000000020816681711721685132943093776702880859375. (Thanks to BigDecimal for proving my point. :-P)
Therefore (absent a decimal floating point or rational number type), outputting it as a string is the only way to get it trimmed to exactly the precision required for display.
Why not use parseFloat?
var someNumber = 123.456;
someNumber = parseFloat(someNumber.toFixed(2));
alert(typeof(someNumber));
//alerts number
I solved it with converting it back to number using JavaScript's Number() function
var x = 2.2873424;
x = Number(x.toFixed(2));
Of course it returns a string. If you wanted to round the numeric variable you'd use Math.round() instead. The point of toFixed is to format the number with a fixed number of decimal places for display to the user.
You can simply use a '+' to convert the result to a number.
var x = 22.032423;
x = +x.toFixed(2); // x = 22.03
May be too late to answer but you can multiple the output with 1 to convert to number again, here is an example.
const x1 = 1211.1212121;
const x2 = x1.toFixed(2)*1;
console.log(typeof(x2));
What would you expect it to return when it's supposed to format a number ? If you have a number you can't pretty much do anything with it because e.g.2 == 2.0 == 2.00 etc. so it has to be a string.
Because its primary use is displaying numbers? If you want to round numbers, use Math.round() with apropriate factors.
To supply an example of why it has to be a string:
If you format 1.toFixed(2) you would get '1.00'.
This is not the same as 1, as 1 does not have 2 decimals.
I know JavaScript isn't exactly a performance language, but chances are you'd get better performance for a rounding if you use something like:
roundedValue = Math.round(value * 100) * 0.01
You should use it like below.
var someNumber: number = 0.000000;
someNumber = Number(someNumber.toFixed(2))
Why not * the result by 1 i.e
someNumber.toFixed(2) * 1
Here's a slightly more functional version of the answer m93a provided.
const toFixedNumber = (toFixTo = 2, base = 10) => num => {
const pow = Math.pow(base, toFixTo)
return +(Math.round(num * pow) / pow)
}
const oneNumber = 10.12323223
const result1 = toFixedNumber(2)(oneNumber) // 10.12
const result2 = toFixedNumber(3)(oneNumber) // 10.123
// or using pipeline-operator
const result3 = oneNumber |> toFixedNumber(2) // 10.12
For others like me that happen upon this very old question, a modern solution:
const roundValue = (num, decimals = 2) => {
let scaling = 10 ** decimals;
return Math.round((num + Number.EPSILON) * scaling) / scaling;
}
ref: https://stackoverflow.com/a/11832950
Be careful using toFixed() and Math.round(), they can produce unexpected results due to the floating point number system:
function toFixedNumber(num, digits, base){
var pow = Math.pow(base||10, digits);
return Math.round(num*pow) / pow;
}
console.log(toFixedNumber(130.795, 2, 10));
// 130.79 (incorrect)
console.log(toFixedNumber(100.795, 2, 10));
// 100.8
console.log(+130.795.toFixed(2));
// 130.79 (incorrect)
console.log(+100.795.toFixed(2));
// 100.8
I recommend using Lodash's _.round() function: https://lodash.com/docs/4.17.15#round
_.round(130.795, 2);
// 130.8

Categories

Resources