u
This commit is contained in:
1 parent
d51eacb8ad
commit
44b3ef27d2
50 files changed
+3141
-9734
No files matched your search
@@ -0,0 +1,106 @@
|
||||
package pgtypex
|
||||
|
||||
import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/shopspring/decimal"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func NumericToString(n pgtype.Numeric) string {
|
||||
if n.Int == nil || n.NaN {
|
||||
return "0.00"
|
||||
}
|
||||
|
||||
// 转成 decimal 保证精度
|
||||
dec := decimal.NewFromBigInt(n.Int, int32(n.Exp))
|
||||
return dec.StringFixed(2) // 保留两位小数
|
||||
}
|
||||
func NumericToDecimal(n pgtype.Numeric) decimal.Decimal {
|
||||
if n.Int == nil || n.NaN {
|
||||
return decimal.Zero
|
||||
}
|
||||
return decimal.NewFromBigInt(n.Int, int32(n.Exp))
|
||||
}
|
||||
|
||||
// TimestampToDateString 转为 "YYYY-MM-DD"
|
||||
func TimestampToDateString(ts pgtype.Timestamp) string {
|
||||
if ts.Time.IsZero() {
|
||||
return ""
|
||||
}
|
||||
return ts.Time.Format("2006-01-02")
|
||||
}
|
||||
|
||||
// TimestampToDateTimeString 转为 "YYYY-MM-DD HH:MM:SS"
|
||||
func TimestampToDateTimeString(ts pgtype.Timestamp) string {
|
||||
if ts.Time.IsZero() {
|
||||
return ""
|
||||
}
|
||||
return ts.Time.Format("2006-01-02 15:04:05")
|
||||
}
|
||||
|
||||
// StringToNumeric 将字符串金额转换为 pgtype.Numeric
|
||||
func StringToNumeric(amountStr string) pgtype.Numeric {
|
||||
if strings.TrimSpace(amountStr) == "" {
|
||||
return pgtype.Numeric{Valid: false}
|
||||
}
|
||||
|
||||
dec, err := decimal.NewFromString(amountStr)
|
||||
if err != nil {
|
||||
return pgtype.Numeric{Valid: false}
|
||||
}
|
||||
|
||||
// 保留两位小数,四舍五入
|
||||
dec = dec.Round(2)
|
||||
|
||||
// 乘以 100 转整数
|
||||
intVal := dec.Mul(decimal.NewFromInt(100)).BigInt()
|
||||
|
||||
return pgtype.Numeric{
|
||||
Int: intVal,
|
||||
Exp: -2, // 固定两位小数
|
||||
NaN: false,
|
||||
Valid: true,
|
||||
}
|
||||
}
|
||||
|
||||
// StringToText 将字符串转换为 pgtype.Text
|
||||
// 空字符串返回零值 Text
|
||||
func StringToText(s string) pgtype.Text {
|
||||
if s == "" {
|
||||
return pgtype.Text{Valid: false}
|
||||
}
|
||||
return pgtype.Text{
|
||||
String: s,
|
||||
Valid: true,
|
||||
}
|
||||
}
|
||||
|
||||
// StringToTimestamp 将字符串解析为 pgtype.Timestamp
|
||||
// 支持格式:YYYY-MM-DD HH:MM:SS 或 YYYY-MM-DD
|
||||
// 解析失败或空字符串返回零值 Timestamp
|
||||
func StringToTimestamp(s string) pgtype.Timestamp {
|
||||
if s == "" {
|
||||
return pgtype.Timestamp{Valid: false}
|
||||
}
|
||||
|
||||
var t time.Time
|
||||
var err error
|
||||
|
||||
layouts := []string{
|
||||
"2006-01-02 15:04:05",
|
||||
"2006-01-02",
|
||||
}
|
||||
|
||||
for _, layout := range layouts {
|
||||
t, err = time.Parse(layout, s)
|
||||
if err == nil {
|
||||
return pgtype.Timestamp{
|
||||
Time: t,
|
||||
Valid: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return pgtype.Timestamp{Valid: false}
|
||||
}
|
||||
Reference in new issue
Block a user