如何用JS格式化rhandsontable渲染表格中指定行的数字?
解决rhandsontable第2行(含新增列)的整数千位分隔格式化需求
直接通过修改hot_cols中的JavaScript渲染函数即可实现,核心是针对第2行(JS行索引为1)的单元格做数值取整和千位分隔处理,替换原代码中对应的渲染逻辑即可。
修改后的完整代码
library(rhandsontable) library(shiny) mydata <- data.frame('Series 1' = c(1,2000.39,3,4),check.names = FALSE) rownames(mydata) <- c('A','B','C','D') ui <- fluidPage( rHandsontableOutput("mytable"), textInput('NewCol', 'Enter new column name'), actionButton("goButton", "Update Table") ) server <- function(input, output) { output$mytable = renderRHandsontable(df()) df <- eventReactive(input$goButton, { if(input$NewCol!="" && !is.null(input$NewCol) && input$goButton>0){ newcol <- data.frame(NROW(mydata)) newcol[2,] <- c(1234.22) names(newcol) <- input$NewCol mydata <<- cbind(mydata, newcol) } rhandsontable(mydata,rowHeaderWidth = 100)%>% hot_cols( renderer = "function(instance, td, row, col, prop, value, cellProperties) { Handsontable.renderers.NumericRenderer.apply(this, arguments); // 第1行(索引0)保持原显示 if(row == 0){ td.innerHTML = `${value}`; } // 第2行(索引1):取整并添加千位分隔符,同时设置背景色 if(row == 1){ const intValue = Math.round(value); td.innerHTML = intValue.toLocaleString(); td.style.background='#eff0f1'; } // 第3、4行(索引2、3)格式化为百分比 if(row == 2 || row == 3){ td.innerHTML = `${Number.parseFloat(value*100)}%`; } }") %>% hot_row(c(2), readOnly = TRUE) # 第2行设为只读 }, ignoreNULL = FALSE) observe(if (!is.null(input$mytable)) mydata <<- hot_to_r(input$mytable)) } shinyApp(ui,server)
关键修改说明
- 取整处理:用
Math.round(value)将数值四舍五入为无小数的整数,也可根据需求改用Math.floor()(向下取整)或Math.ceil()(向上取整); - 千位分隔:利用JavaScript原生的
toLocaleString()方法,自动为整数添加千位分隔符,无需手动拼接字符串; - 代码整合:将第2行的背景色设置合并到同一条件判断中,避免重复逻辑。
这样修改后,无论是原有列还是新增列,第2行的数值都会统一显示为带千位分隔的无小数整数,完全满足需求。
内容的提问来源于stack exchange,提问作者Village.Idyot
相关产品推荐
相关产品推荐

