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
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
Share Improve this question asked Apr 29, 2015 at 10:36 GusGus 9534 gold badges15 silver badges30 bronze badges 3- You're confusing rounding with formatting. – Dave Newton Commented Apr 29, 2015 at 10:39
- try using this: a.toFixed(2) // this fixes to two decimal places – Kop4lyf Commented Apr 29, 2015 at 10:40
- possible duplicate of JavaScript: formatting number with exactly two decimals – GillesC Commented Apr 29, 2015 at 10:47
5 Answers
Reset to default 4(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 es 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 remend using a library to format your numbers http://numeraljs./
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/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