1,450.45
import { FormatNumber, Text } from "@chakra-ui/react"
const Demo = () => {
return (
<Text textStyle="lg">
<FormatNumber value={1450.45} />
</Text>
)
}
用法
¥Usage
数字格式化逻辑由原生 Intl.NumberFormat
API 处理,并进行智能缓存,以避免在使用相同语言环境和选项时出现性能问题。
¥The number formatting logic is handled by the native Intl.NumberFormat
API and
smartly cached to avoid performance issues when using the same locale and
options.
import { FormatNumber } from "@chakra-ui/react"
<FormatNumber value={1000} />
示例
¥Examples
百分比
¥Percentage
使用 style=percentage
属性将数字格式更改为百分比。
¥Use the style=percentage
prop to change the number format to 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>
)
}
货币
¥Currency
使用 style=currency
属性将数字格式更改为货币。
¥Use the style=currency
prop to change the number format to 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>
)
}
语言环境
¥Locale
将 FormatNumber
组件封装在 LocaleProvider
中以更改语言环境。
¥Wrap the FormatNumber
component within the LocaleProvider
to change the
locale.
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>
)
}
单元
¥Unit
使用 style=unit
属性将数字格式更改为单位。
¥Use the style=unit
prop to change the number format to 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>
)
}
紧凑符号
¥Compact Notation
使用 notation=compact
属性将数字格式更改为紧凑符号。
¥Use the notation=compact
prop to change the number format to compact notation.
1.5M
import { FormatNumber, Text } from "@chakra-ui/react"
const Demo = () => {
return (
<Text textStyle="lg">
<FormatNumber value={1500000} notation="compact" compactDisplay="short" />
</Text>
)
}
属性
¥Props
FormatNumber
组件除了支持以下属性外,还支持所有 Intl.NumberFormat
选项:
¥The FormatNumber
component supports all Intl.NumberFormat
options in
addition to the following props:
Prop | Default | Type |
---|---|---|
value * | number The number to format |