LibreOffice Calc Basic如何通过代码实现数值保留两位小数
实现单元格保留两位小数的代码调整方案
方案1:仅调整显示格式(保留原始数值精度,推荐)
该方案不会修改单元格存储的实际数值,仅调整显示效果,后续计算仍使用原始值,无精度损失:
Dim currDoc As Object Dim currSheet As Object Dim cell As Object Dim fmtId As Long currDoc = ThisComponent currSheet = currDoc.sheets(0) ' 示例:操作A1单元格,可按需替换为你要操作的单元格对象 cell = currSheet.getCellRangeByName("A1") cell.Value = cDbl(cell.Value) ' 查询两位小数的格式ID,不存在则新建 fmtId = currDoc.NumberFormats.queryKey("0.00", cell.CharLocale, False) If fmtId = -1 Then fmtId = currDoc.NumberFormats.addNew("0.00", cell.CharLocale) End If cell.NumberFormat = fmtId
如果你的系统区域默认使用逗号作为小数分隔符,设置后会直接显示为100,00的效果。
方案2:直接修改实际数值为两位小数
如果你需要单元格存储的实际值本身就是保留两位小数后的结果,可使用四舍五入逻辑:
Dim currDoc As Object Dim currSheet As Object Dim cell As Object Dim fmtId As Long currDoc = ThisComponent currSheet = currDoc.sheets(0) cell = currSheet.getCellRangeByName("A1") ' 四舍五入保留两位小数,如需截断可替换为 Int(cDbl(cell.Value)*100)/100 cell.Value = Round(cDbl(cell.Value), 2) ' 查询两位小数的格式ID,不存在则新建 fmtId = currDoc.NumberFormats.queryKey("0.00", cell.CharLocale, False) If fmtId = -1 Then fmtId = currDoc.NumberFormats.addNew("0.00", cell.CharLocale) End If cell.NumberFormat = fmtId
补充说明
- 不建议直接给
cell.Formula赋值数值,Formula属性用于存储公式表达式,存储纯数值使用Value属性更规范。 - 如果你需要强制无论区域设置都使用逗号作为小数分隔符,可将格式字符串替换为
"0\,00"即可。
内容的提问来源于stack exchange,提问作者Tobi S
相关产品推荐
相关产品推荐

