mirror of
https://github.com/josdejong/mathjs.git
synced 2026-01-25 15:07:57 +00:00
Added splitUnit function
This commit is contained in:
parent
ff53b04dca
commit
58e3247c27
@ -11,6 +11,7 @@ function factory (type, config, load, typed, math) {
|
||||
var divide = load(require('../../function/arithmetic/divideScalar'));
|
||||
var pow = load(require('../../function/arithmetic/pow'));
|
||||
var abs = load(require('../../function/arithmetic/abs'));
|
||||
var fix = load(require('../../function/arithmetic/fix'));
|
||||
var equal = load(require('../../function/relational/equal'));
|
||||
var isNumeric = load(require('../../function/utils/isNumeric'));
|
||||
var format = load(require('../../function/string/format'));
|
||||
@ -856,7 +857,12 @@ function factory (type, config, load, typed, math) {
|
||||
* @return {number | BigNumber | Fraction} Returns the unit value
|
||||
*/
|
||||
Unit.prototype.toNumeric = function (valuelessUnit) {
|
||||
var other = this.to(valuelessUnit);
|
||||
var other = this;
|
||||
if(valuelessUnit) {
|
||||
// Allow getting the numeric value without converting to a different unit
|
||||
other = this.to(valuelessUnit);
|
||||
}
|
||||
|
||||
if(other._isDerived()) {
|
||||
return other._denormalize(other.value);
|
||||
}
|
||||
@ -1165,6 +1171,37 @@ function factory (type, config, load, typed, math) {
|
||||
return bestPrefix;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns an array of units whose sum is equal to this unit
|
||||
* @memberof Unit
|
||||
* @param {Array} [parts] An array of strings or valueless units.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* var u = new Unit(1, 'm');
|
||||
* u.splitUnit(['feet', 'inch']);
|
||||
* [ 3 feet, 3.3700787401575 inch ]
|
||||
*
|
||||
* @return {Array} An array of units.
|
||||
*/
|
||||
Unit.prototype.splitUnit = function(parts) {
|
||||
|
||||
var x = this.clone();
|
||||
var ret = [];
|
||||
for(var i=0; i<parts.length; i++) {
|
||||
x = x.to(parts[i]);
|
||||
if(i==parts.length-1) break;
|
||||
// fix rounds a number towards 0
|
||||
var fixedVal = fix(x.toNumeric());
|
||||
var y = new Unit(fixedVal, parts[i].toString());
|
||||
ret.push(y);
|
||||
x = subtract(x, y);
|
||||
}
|
||||
ret.push(x);
|
||||
|
||||
return ret;
|
||||
};
|
||||
|
||||
var PREFIXES = {
|
||||
NONE: {
|
||||
'': {name: '', value: 1, scientific: true}
|
||||
|
||||
@ -8,6 +8,9 @@ module.exports = [
|
||||
// create new units
|
||||
require('./function/createUnit'),
|
||||
|
||||
// split units
|
||||
require('./function/splitUnit'),
|
||||
|
||||
// physical constants
|
||||
require('./physicalConstants')
|
||||
];
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user