Function format #
将任何类型的值格式化为字符串。
Syntax #
math.format(value)
math.format(value, options)
math.format(value, precision)
math.format(value, callback)
Where #
value: *要格式化的值options: Object包含格式化选项的对象。可用选项notation: string数字表示法。从以下选项中选择'fixed'始终使用常规数字表示法。例如'123.40'和'14000000''exponential'始终使用指数表示法。例如'1.234e+2'和'1.4e+7''engineering'始终使用工程表示法:始终使用指数表示法,并将指数选择为3的倍数。例如'123.4e+0'和'14.0e+6''auto'(默认) 对于绝对值介于lower和upper边界之间的数字,使用常规数字表示法,其他情况则使用指数表示法。包含下边界,排除上边界。例如'123.4'和'1.4e7'。'bin'、'oct'或'hex'使用二进制、八进制或十六进制表示法格式化数字。例如'0b1101'和'0x10fe'。
wordSize: number | BigNumber用于二进制、八进制或十六进制表示法格式化的位数。仅与notation选项的'bin'、'oct'或'hex'值一起使用。定义此选项时,值将作为指定字大小的有符号二进制补码整数进行格式化,并在输出后附加大小后缀。例如format(-1, {notation: 'hex', wordSize: 8}) === '0xffi8'。默认值为 undefined。precision: number | BigNumber限制格式化值的位数。对于常规数字,必须是介于0和16之间的数字。对于 bignumbers,最大值取决于配置的精度,请参阅函数config()。对于'exponential'、'engineering'和'auto'表示法,precision定义返回的有效数字总数。对于'fixed'表示法,precision定义小数点后的有效数字位数。precision默认值为 undefined。lowerExp: number在notation='auto'时,用于确定带有指数的值格式化的下限的指数。默认值为-3。upperExp: number在notation='auto'时,用于确定带有指数的值格式化的上限的指数。默认值为5。fraction: string。可用值:'ratio'(默认) 或'decimal'。例如,当配置为'ratio'时,format(fraction(1, 3))将输出'1/3';当配置为'decimal'时,将输出'0.(3)'。truncate: number。指定返回字符串的最大允许长度。如果长度超过此限制,则删除多余的字符并用'...'替换。
callback: function一个自定义格式化函数,将为value中的所有数值元素调用,例如矩阵的所有元素,或复数的实部和虚部。此回调可用于覆盖内置的数字表示法,并使用任何类型的格式化。函数callback以value作为参数进行调用,并必须返回一个字符串。
Parameters #
| Parameter | Type | Description |
|---|---|---|
value |
* | 要转换为字符串的值 |
options |
Object | Function | number | 格式化选项 |
Returns #
| Type | Description |
|---|---|
| string | 格式化后的值 |
Throws #
Type | Description —- | ———–
Examples #
math.format(6.4) // returns '6.4'
math.format(1240000) // returns '1.24e+6'
math.format(1/3) // returns '0.3333333333333333'
math.format(1/3, 3) // returns '0.333'
math.format(21385, 2) // returns '21000'
math.format(12e8, {notation: 'fixed'}) // returns '1200000000'
math.format(2.3, {notation: 'fixed', precision: 4}) // returns '2.3000'
math.format(52.8, {notation: 'exponential'}) // returns '5.28e+1'
math.format(12400, {notation: 'engineering'}) // returns '12.4e+3'
math.format(2000, {lowerExp: -2, upperExp: 2}) // returns '2e+3'
function formatCurrency(value) {
// return currency notation with two digits:
return '$' + value.toFixed(2)
// you could also use math.format inside the callback:
// return '$' + math.format(value, {notation: 'fixed', precision: 2})
}
math.format([2.1, 3, 0.016], formatCurrency) // returns '[$2.10, $3.00, $0.02]'