javascript:将函数的输出更改为指定的小数位
Posted
技术标签:
【中文标题】javascript:将函数的输出更改为指定的小数位【英文标题】:javascript: Alter the output of a function to the specified decimal place 【发布时间】:2016-10-07 04:16:31 【问题描述】:我的 javascript 不是很好,但最近需要使用库来输出聚合表。正在使用fin-hypergrid。
有一部分我需要在一个对象中插入一个求和函数(本例中为 rollups.sum(11)),以便它可以计算表中的聚合值,如下所示:
aggregates = Value: rollups.sum(11)
我想将此值更改为返回 2 位小数并尝试:
rollups.sum(11).toFixed(2)
但是,它给出了错误:“rollups.sum(...).toFixed is not a function”
如果我尝试类似:
parseFloat(rollups.sum(11)).toFixed(2)
它抛出错误:“无法分配给 (new String("NaN")) 的属性:不是对象”
所以它必须是一个函数对象。
我想知道是否有办法改变函数 rollups.sum(11) 以返回带 2 个小数位的函数对象?
(side info: rollups.sum(11) 来自一个模块:
sum: function(columnIndex)
return sum.bind(this, columnIndex);
)
抱歉,由于数据机密性问题,我无法在此处发布示例输出。 但是,这是我遵循的示例中的代码。我基本上需要更改 rollups.whatever 以给出小数位。这里sum(11)中的“11”指的是一个“列索引”。
window.onload = function()
var Hypergrid = fin.Hypergrid;
var drillDown = Hypergrid.drillDown;
var TreeView = Hypergrid.TreeView;
var GroupView = Hypergrid.GroupView;
var AggView = Hypergrid.AggregationsView;
// List of properties to show as checkboxes in this demo's "dashboard"
var toggleProps = [
label: 'Grouping',
ctrls: [
name: 'treeview', checked: false, setter: toggleTreeview ,
name: 'aggregates', checked: false, setter: toggleAggregates ,
name: 'grouping', checked: false, setter: toggleGrouping
]
];
function derivedPeopleSchema(columns)
// create a hierarchical schema organized by alias
var factory = new Hypergrid.ColumnSchemaFactory(columns);
factory.organize(/^(one|two|three|four|five|six|seven|eight)/i, key: 'alias' );
var columnSchema = factory.lookup('last_name');
if (columnSchema)
columnSchema.defaultOp = 'IN';
//factory.lookup('birthState').opMenu = ['>', '<'];
return factory.schema;
var customSchema = [
name: 'last_name', type: 'number', opMenu: ['=', '<', '>'], opMustBeInMenu: true ,
name: 'total_number_of_pets_owned', type: 'number' ,
name: 'height', type: 'number' ,
'birthDate',
'birthState',
'employed',
name: 'income', type: 'number' ,
name: 'travel', type: 'number'
];
var peopleSchema = customSchema; // or try setting to derivedPeopleSchema
var gridOptions =
data: people1,
schema: peopleSchema,
margin: bottom: '17px'
,
grid = window.g = new Hypergrid('div#json-example', gridOptions),
behavior = window.b = grid.behavior,
dataModel = window.m = behavior.dataModel,
idx = behavior.columnEnum;
console.log('Fields:'); console.dir(behavior.dataModel.getFields());
console.log('Headers:'); console.dir(behavior.dataModel.getHeaders());
console.log('Indexes:'); console.dir(idx);
var treeView, dataset;
function setData(data, options)
options = options || ;
if (data === people1 || data === people2)
options.schema = peopleSchema;
dataset = data;
behavior.setData(data, options);
idx = behavior.columnEnum;
// Preset a default dialog options object. Used by call to toggleDialog('ColumnPicker') from features/ColumnPicker.js and by toggleDialog() defined herein.
grid.setDialogOptions(
//container: document.getElementById('dialog-container'),
settings: false
);
// add a column filter subexpression containing a single condition purely for demo purposes
if (false) // eslint-disable-line no-constant-condition
grid.getGlobalFilter().columnFilters.add(
children: [
column: 'total_number_of_pets_owned',
operator: '=',
operand: '3'
],
type: 'columnFilter'
);
window.vent = false;
//functions for showing the grouping/rollup capabilities
var rollups = window.fin.Hypergrid.analytics.util.aggregations,
aggregates =
totalPets: rollups.sum(2),
averagePets: rollups.avg(2),
maxPets: rollups.max(2),
minPets: rollups.min(2),
firstPet: rollups.first(2),
lastPet: rollups.last(2),
stdDevPets: rollups.stddev(2)
,
groups = [idx.BIRTH_STATE, idx.LAST_NAME, idx.FIRST_NAME];
var aggView, aggViewOn = false, doAggregates = false;
function toggleAggregates()
if (!aggView)
aggView = new AggView(grid, );
aggView.setPipeline( includeSorter: true, includeFilter: true );
if (this.checked)
grid.setAggregateGroups(aggregates, groups);
aggViewOn = true;
else
grid.setAggregateGroups([], []);
aggViewOn = false;
function toggleTreeview()
if (this.checked)
treeView = new TreeView(grid, treeColumn: 'State' );
treeView.setPipeline( includeSorter: true, includeFilter: true );
treeView.setRelation(true, true);
else
treeView.setRelation(false);
treeView = undefined;
delete dataModel.pipeline; // restore original (shared) pipeline
behavior.setData(); // reset with original pipeline
var groupView, groupViewOn = false;
function toggleGrouping()
if (!groupView)
groupView = new GroupView(grid, );
groupView.setPipeline( includeSorter: true, includeFilter: true );
if (this.checked)
grid.setGroups(groups);
groupViewOn = true;
else
grid.setGroups([]);
groupViewOn = false;
【问题讨论】:
能否提供求和函数的示例输出?我已经在两种情况下测试了数字和字符串的返回输出parseFloat(rollups.sum(11)).toFixed(2)
工作正常
你能显示 sum(11) 的返回值是什么,所以我可以看看你正在处理什么样的数据结构。
很抱歉,由于数据是机密的,我无法发布示例输出。但是,我在这里虔诚地遵循了一个示例link。基本上,如果您单击“聚合”复选框,它将对值求和。我只想尝试更改总和格式以输出 2 位小数。该示例的脚本可以在这里找到link。
【参考方案1】:
你可以试试:
(rollups.sum(11)).toFixed(2)
括号中的数字似乎使浏览器绕过标识符不能在数字文字后立即开始的限制
编辑#2:
//all formatting and rendering per cell can be overridden in here
dataModel.getCell = function(config, rendererName)
if(aggViewOn)
if(config.columnName == "total_pets")
if(typeof(config.value) == 'number')
config.value = config.value.toFixed(2);
else if(config.value && config.value.length == 3 && typeof(config.value[1]) == 'number')
config.value = config.value[1].toFixed(2);
return grid.cellRenderers.get(rendererName);
;
【讨论】:
感谢博德!我试过了,但它返回一个错误:TypeError: rollups.sum(...).toFixed is not a function。我认为任何修改最终都应该返回一个函数对象。 如何覆盖单元格渲染,@NoobPoke?请看看我编辑的答案 嗨,Bod,我将此代码放在聚合切换定义之后。然后所有的单元格都变成黄色并且有文本“renderer is undefined” @NoobPoke,我忘记了其余的功能,第二个修改可能是第一个,我希望:)以上是关于javascript:将函数的输出更改为指定的小数位的主要内容,如果未能解决你的问题,请参考以下文章
将 KeyboardType 更改为带小数点的数字键盘以用于设置首选项