JS - format number with two decimal places without rounding
I would format the number with two decimal places without rounding. So I excluded the toFixed () function.
I 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 digit a is zero and that was removed, how could I keep it and have a = 1.80? Thanks you
source to share
Rounding of a number is associated with a change in its value and must be performed using mathematical operations (Math.floor, Math.ceil, Math.round, ...).
The formatting number is how numbers are displayed to the user (for example, date formatting).
Javascript does not come with an acceptable built-in number formatting tool.
You can always play with rounding to make javascript print the number the way you want, but you end up writing a lot (probably buggy) code.
I would recommend using a library to format your numbers http://numeraljs.com/
numeral(number).format('0.00');
source to share
you only need to use toFixed () and pass a number like 2, after which it is displayed after. two decimal numbers, e.g. 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>
Hope this helps you. and also see this jsfiddle link http://jsfiddle.net/RGerb/394/
source to share