1,450.45
import { FormatNumber, Text } from "@chakra-ui/react"
const Demo = () => {
return (
<Text textStyle="lg">
<FormatNumber value={1450.45} />
</Text>
)
}
用法
数字格式化逻辑由原生的Intl.NumberFormat
API 处理,并智能缓存以避免在使用相同区域设置和选项时出现性能问题。
import { FormatNumber } from "@chakra-ui/react"
<FormatNumber value={1000} />
示例
百分比
使用 style=percentage
属性将数字格式更改为百分比。
14.50%
import { FormatNumber, Text } from "@chakra-ui/react"
const Demo = () => {
return (
<Text textStyle="lg">
<FormatNumber
value={0.145}
style="percent"
maximumFractionDigits={2}
minimumFractionDigits={2}
/>
</Text>
)
}
货币
使用 style=currency
属性将数字格式更改为货币。
$1,234.45
import { FormatNumber, Text } from "@chakra-ui/react"
const Demo = () => {
return (
<Text textStyle="lg">
<FormatNumber value={1234.45} style="currency" currency="USD" />
</Text>
)
}
区域设置
将 FormatNumber
组件包裹在 LocaleProvider
中以更改区域设置。
de-DE
1.450,45zh-CN
1,450.45import { FormatNumber, HStack, LocaleProvider, Text } from "@chakra-ui/react"
const Demo = () => {
return (
<Text textStyle="lg">
<HStack>
<Text fontWeight="medium">de-DE</Text>
<LocaleProvider locale="de-DE">
<FormatNumber value={1450.45} />
</LocaleProvider>
</HStack>
<HStack>
<Text fontWeight="medium">zh-CN</Text>
<LocaleProvider locale="zh-CN">
<FormatNumber value={1450.45} />
</LocaleProvider>
</HStack>
</Text>
)
}
单位
使用 style=unit
属性将数字格式更改为单位。
384.4 km
import { FormatNumber, Text } from "@chakra-ui/react"
const Demo = () => {
return (
<Text textStyle="lg">
<FormatNumber value={384.4} style="unit" unit="kilometer" />
</Text>
)
}
紧凑记数法
使用 notation=compact
属性将数字格式更改为紧凑记数法。
1.5M
import { FormatNumber, Text } from "@chakra-ui/react"
const Demo = () => {
return (
<Text textStyle="lg">
<FormatNumber value={1500000} notation="compact" compactDisplay="short" />
</Text>
)
}
属性
FormatNumber
组件支持所有 Intl.NumberFormat
选项以及以下属性:
属性 | 默认值 | 类型 |
---|---|---|
value * | number 要格式化的数字 |