CSS Calc - Round Down with Two Decimal Cases

Formatting a number with exactly two decimals in JavaScript

To format a number using fixed-point notation, you can simply use the toFixed method:

(10.8).toFixed(2); // "10.80"

var num = 2.4;
alert(num.toFixed(2)); // "2.40"

Note that toFixed() returns a string.

IMPORTANT: Note that toFixed does not round 90% of the time, it will return the rounded value, but for many cases, it doesn't work.

For instance:

2.005.toFixed(2) === "2.00"

UPDATE:

Nowadays, you can use the Intl.NumberFormat constructor. It's part of the ECMAScript Internationalization API Specification (ECMA402). It has pretty good browser support, including even IE11, and it is fully supported in Node.js.

const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});

console.log(formatter.format(2.005)); // "2.01"
console.log(formatter.format(1.345)); // "1.35"

Rounding numbers in Sass and adjusting the amount of decimals

From the SASS change logs:

The numeric precision of numbers in Sass can now be set using the --precision option to the command line. Additionally, the default number of digits of precision in Sass output can now be changed by setting Sass::Script::Number.precision to an integer (defaults to 3). Since this value can now be changed, the PRECISION constant in Sass::Script::Number has been deprecated. In the unlikely event that you were using it in your code, you should now use Sass::Script::Number.precision_factor instead.

This was added in SASS 3.1.8.

Decimal places in CSS percentage

There are probably many solutions for your problem, I would suggest these:

  1. Round on 2 decimals by yourself for all but one, than reduce from
    total width for last one.
  2. Use table or display: table, than the
    browser will fix the widths by itself.

Truncate number to two decimal places without rounding

Convert the number into a string, match the number up to the second decimal place:

function calc(theform) {

var num = theform.original.value, rounded = theform.rounded

var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]

rounded.value = with2Decimals

}
<form onsubmit="return calc(this)">

Original number: <input name="original" type="text" onkeyup="calc(form)" onchange="calc(form)" />

<br />"Rounded" number: <input name="rounded" type="text" placeholder="readonly" readonly>

</form>

Can numbers be rounded (math term) using LESS CSS?

Yes they can:

line-height: ceil(@height * .666);      // 20px (round up)
line-height: floor(@height * .666); // 19px (round down)
line-height: round(@height * .666); // 20px (round to closest integer)
line-height: round(@height * .666, 1); // 20.0px (round to 1 decimal place)


Related Topics



Leave a reply



Submit