首页 > 解决方案 > 在 JavaScript/Vue 中是否有相当于 Python 的格式规范迷你语言?

问题描述

我正在开发一个 Django 项目,该项目通过矢量图块将数据发送到 Vue(tify) 前端。由于这种架构,在 Django 模型实例上运行 Python 是不切实际的。矢量切片在数据库内部生成,查询集未在 Django 后端实现。

此外,我们宁愿以原始类型发送数据并在前端处理格式。从 Python 我知道Format Specification Mini-Language。JavaScript/Vue/Vuetify 中是否有等价物?


示例:在 Pythonf"{1/9:.4f}"中会导致'0.1111'.


相关:这个对 JavaScript 的回答等同于 printf/String.Format。我正在寻找更灵活的东西,就像 Format Specification Mini-Language

标签: javascriptnode.jsvue.jsformattingvuetify.js

解决方案


最好和最灵活的方法应该是Inlt,一个 js 命名空间,其中包含许多用于各种数据类型的格式化程序。

一些例子:

new Intl.NumberFormat().format(12345)
// 12,345

new Intl.NumberFormat('en-US', { maximumSignificantDigits: 4}).format(1.2345678)
// 1.235 (Notice the rounding)

new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP' }).format(9002.20)
// £9,002.20

new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(9002.20)
// 9.002,20 €

new Intl.NumberFormat().formatToParts(12345.678)
/*
[
   { "type":"integer", "value":"12" },
   { "type":"group", "value":"," },
   { "type":"integer", "value":"345" },
   { "type":"decimal", "value":"." },
   { "type":"fraction", "value":"678" }
]

(参考)

new Intl.DateTimeFormat('default', {
  hour: 'numeric',
  minute: 'numeric',
  second: 'numeric'
}).format(date)
// → '2:00:00 pm

new Intl.DateTimeFormat('en-US', {
  year: 'numeric',
  month: 'numeric',
  day: 'numeric'
}).format(date)
// → '12/19/2012'

(参考)


推荐阅读