phaser/src/math/RoundTo.js

47 lines
1.2 KiB
JavaScript
Raw Normal View History

2018-02-12 16:01:20 +00:00
/**
* @author Richard Davey <rich@photonstorm.com>
2023-01-02 17:36:27 +00:00
* @copyright 2013-2023 Photon Storm Ltd.
2019-05-10 15:15:04 +00:00
* @license {@link https://opensource.org/licenses/MIT|MIT License}
2018-02-12 16:01:20 +00:00
*/
2017-10-06 03:52:41 +00:00
/**
2019-04-17 09:52:23 +00:00
* Round a value to the given precision.
2022-02-28 14:29:51 +00:00
*
2019-04-17 09:52:23 +00:00
* For example:
2022-02-28 14:29:51 +00:00
*
2019-04-17 09:52:23 +00:00
* ```javascript
* RoundTo(123.456, 0) = 123
* RoundTo(123.456, 1) = 120
* RoundTo(123.456, 2) = 100
* ```
2022-02-28 14:29:51 +00:00
*
2019-04-17 09:52:23 +00:00
* To round the decimal, i.e. to round to precision, pass in a negative `place`:
2022-02-28 14:29:51 +00:00
*
2019-04-17 09:52:23 +00:00
* ```javascript
* RoundTo(123.456789, 0) = 123
* RoundTo(123.456789, -1) = 123.5
* RoundTo(123.456789, -2) = 123.46
* RoundTo(123.456789, -3) = 123.457
* ```
2017-10-06 03:52:41 +00:00
*
* @function Phaser.Math.RoundTo
* @since 3.0.0
*
* @param {number} value - The value to round.
2020-11-23 10:22:13 +00:00
* @param {number} [place=0] - The place to round to. Positive to round the units, negative to round the decimal.
* @param {number} [base=10] - The base to round in. Default is 10 for decimal.
2017-10-06 03:52:41 +00:00
*
* @return {number} The rounded value.
2017-10-06 03:52:41 +00:00
*/
var RoundTo = function (value, place, base)
{
if (place === undefined) { place = 0; }
if (base === undefined) { base = 10; }
var p = Math.pow(base, -place);
return Math.round(value * p) / p;
};
module.exports = RoundTo;