Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              // any number of function arguments followed by expected return value
// e.g. [number, precision, expected]
const testCases = [
  [1.005, 2, 1.01],
  [2.1755465135353, 4, 2.1755],
  [1.004999, 2, 1],
];

// Functions from answers and comments to
// https://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places-only-if-necessary
// function names correspond to user names
const testedFunctions = [
  aleha,
  Dmytro_Medvid,
  // Dmytro_Medvid_js,
  KFish,
  Brian_Ustas, 
  cronvel, 
  caliche2000,
  Matas_Vaitkevicius,
  Rob_Evans,
  fellow_stranger,
  Ross,
  // Ross_js,
];

// call each function with the arguments and expected return values specified by testCases
runTests(testedFunctions, testCases);

// Accepted answer — WRONG!
function Brian_Ustas(num, precision) {
  const f = 10 ** precision;
  return Math.round(num * f) / f
}

function cronvel(num, precision) {
  const f = 10 ** precision;
  return Math.round((num + Number.EPSILON) * f) / f;
}

function caliche2000(number, precision = 0) {
  var num = number.toString().replace(",", "");
  var integer, decimal, significantDigit;

  if (num.indexOf(".") > 0 && num.substring(num.indexOf(".") + 1).length > precision && precision > 0) {
      integer = parseInt(num).toString();
      decimal = num.substring(num.indexOf(".") + 1);
      significantDigit = Number(decimal.substr(precision, 1));

      if (significantDigit >= 5) {
          decimal = (Number(decimal.substr(0, precision)) + 1).toString();
          return integer + "." + decimal;
      } else {
          decimal = (Number(decimal.substr(0, precision)) + 1).toString();
          return integer + "." + decimal;
      }
  }
  else if (num.indexOf(".") > 0) {
      integer = parseInt(num).toString();
      decimal = num.substring(num.indexOf(".") + 1);
      significantDigit = num.substring(num.length - 1, 1);

      if (significantDigit >= 5) {
          decimal = (Number(decimal) + 1).toString();
          return integer + "." + decimal;
      } else {            
          return integer + "." + decimal;
      }
  }
  return number;
}

function KFish(num, precision) {
  const DecimalPrecision = (function(){
    if (Number.EPSILON === undefined) {
      Number.EPSILON = Math.pow(2, -52);
    }
    this.round = function(n, p=2){
      let r = 0.5 * Number.EPSILON * n;
      let o = 1; while(p-- > 0) o *= 10;
      if(n < 0)
        o *= -1;
      return Math.round((n + r) * o) / o;
    }
    this.ceil = function(n, p=2){
      let r = 0.5 * Number.EPSILON * n;
      let o = 1; while(p-- > 0) o *= 10;
      if(n < 0)
        o *= -1;
      return Math.ceil((n + r) * o) / o;
    }
    this.floor = function(n, p=2){
      let r = 0.5 * Number.EPSILON * n;
      let o = 1; while(p-- > 0) o *= 10;
      if(n < 0)
        o *= -1;
      return Math.floor((n + r) * o) / o;
    }
    return this;
  })();
  return DecimalPrecision.round(num, precision);
};

function Matas_Vaitkevicius(num, precision) {
  return num.toPrecision(precision);
}

function Rob_Evans(value, decimalPlaces = 0) {
    const multiplier = Math.pow(10, decimalPlaces);
    return Math.round(value * multiplier + Number.EPSILON) / multiplier;
};

function fellow_stranger(num, precision) {
  return Math.round((num + 0.00001) * precision) / precision;
}

function aleha(num, _prec) {
  var precalculatedPrecisions = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10];
  _precision = precalculatedPrecisions[_prec]
  return Math.round(num * _precision + 1e-14) / _precision ;
}

function Dmytro_Medvid(amount: number, decimals: number) {
    return Number(Math.round(Number(`${amount}e${decimals}`)) + `e-${decimals}`);
}
function Dmytro_Medvid_js(amount, decimals) {
    return Number(Math.round(Number(`${amount}e${decimals}`)) + `e-${decimals}`);
}

function Ross(decimal: number, decimalPoints: number): number{
    let roundedValue = Math.round(decimal * Math.pow(10, decimalPoints)) / Math.pow(10, decimalPoints);

    console.log(`Rounded ${decimal} to ${roundedValue}`);
    return roundedValue;
}
function Ross_js(decimal, decimalPoints) {
    let roundedValue = Math.round(decimal * Math.pow(10, decimalPoints)) / Math.pow(10, decimalPoints);

    console.log(`Rounded ${decimal} to ${roundedValue}`);
    return roundedValue;
}

/*     My super cool testing framework 👌    *\
               can be found at
\*   https://codepen.io/hyvyys/pen/oNvwNrJ   */



            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console