2 个不稳定版本

0.2.0 2022年11月14日
0.1.0 2022年11月11日

#175 in 数值格式化

Download history 36/week @ 2024-03-04 42/week @ 2024-03-11 26/week @ 2024-03-18 34/week @ 2024-03-25 118/week @ 2024-04-01 137/week @ 2024-04-08 171/week @ 2024-04-15 178/week @ 2024-04-22 70/week @ 2024-04-29 65/week @ 2024-05-06 98/week @ 2024-05-13 101/week @ 2024-05-20 66/week @ 2024-05-27 42/week @ 2024-06-03 70/week @ 2024-06-10 40/week @ 2024-06-17

220 次每月下载
用于 toprs

MIT/Apache

33KB
647

formato

轻松将数字格式化为字符串表示形式
适用于整数(u8-u128 和 i8-i128)和浮点数(f32, f64)
允许您指定千位分隔符的位置、小数位数、正数、负数和零的不同格式。例如。

  • 1,000,000
  • 0012
  • (4 234.56)

类似于 Excel 和 C# 中的数值格式化

简单示例

use formato::{Formato,FormatOptions};
assert_eq!("001", 1.formato("000"));
assert_eq!("1,234", 1234.formato("#,###"));
assert_eq!("1,234.56", (1234.5632).formato("N2")); 
assert_eq!("(1,234)", (-1234).formato("#,##0 ;(#,##0);-"));

let ops=FormatOptions::default()
        .with_thousands(" ")
        .with_decimal(",");
assert_eq!("1 234,32", 1234.321.formato_ops("#,###.00",&ops));        

占位符

  • "0" 如果有一个数字则替换为数字,否则为 0
  • "#" 如果有一个数字则替换为数字,否则忽略
assert_eq!("001", 1.formato("000"));
assert_eq!("1", 1.formato("###"));
assert_eq!("01", 1.formato("#00"));

内置格式

其中 'd' 是可选的小数位数。省略时默认为 2

  • "Fd": 使用固定小数位数进行格式化
  • "Nd": 使用千位分隔符和固定小数位数进行格式化
let num:f64 = 1234.1234;
 assert_eq!("1234.12", num.formato("F"));
 assert_eq!("1234.1", num.formato("F1"));
 assert_eq!("1,234.12", num.formato("N"));
 assert_eq!("1,234.1", num.formato("N1"));

舍入

省略小数部分时,如果下一位数字是 5 或以上,则进行舍入

assert_eq!("1,234.57", 1234.5678.formato("#,###.##"));
assert_eq!("$ 10,000.00", 9999.996.formato("$ #,###.##")); 

千位分隔符

assert_eq!("1,234", 1234.formato("#,###"));

//pattern is repeated for more significant digits
assert_eq!("1,000,000", 1_000_000.formato("#,###"));

//Indian notation - left most pattern is repeated for more significant digits
assert_eq!("10,00,000", 1_000_000.formato("#,##,###"));

货币和其他字符

//formato ignores characters other than #0,. and includes them as is
assert_eq!("$ 1,234.00", 1234.formato("$ #,###.00"));
assert_eq!("oh wow!❤1,234✔", 1234.formato("oh wow!❤#,###✔"));

自定义千位和十位分隔符

"," 设置分组位置(在整数部分重复最后找到的图案。在十进制部分作为正常字符处理)

let ops=FormatOptions::default()
        .with_thousands(" ")
        .with_decimal(",");
assert_eq!("1 234,00", 1234.formato_ops("#,###.00",&ops));

正数、负数、零的格式

";" 可选地分隔正数、负数、零的格式。例如 0;(0);-

let my_format = "#,###.00 ;(#,###.00);- ";
assert_eq!("1,234.57 ", 1234.567.formato(my_format));
assert_eq!("(1,234.57)", (-1234.567).formato(my_format));
assert_eq!("- ", 0.formato(my_format));

无运行时依赖