aboutsummaryrefslogtreecommitdiff
path: root/v_windows/v/vlib/strconv/format.v
blob: e11a6042071185ae5d60b5f9cb6234f7e10e6e52 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
module strconv

/*
printf/sprintf V implementation

Copyright (c) 2020 Dario Deledda. All rights reserved.
Use of this source code is governed by an MIT license
that can be found in the LICENSE file.

This file contains the printf/sprintf functions
*/
import strings

pub enum Align_text {
	right = 0
	left
	center
}

/*
Float conversion utility
*/
const (
	// rounding value
	dec_round = [
		f64(0.5),
		0.05,
		0.005,
		0.0005,
		0.00005,
		0.000005,
		0.0000005,
		0.00000005,
		0.000000005,
		0.0000000005,
		0.00000000005,
		0.000000000005,
		0.0000000000005,
		0.00000000000005,
		0.000000000000005,
		0.0000000000000005,
		0.00000000000000005,
		0.000000000000000005,
		0.0000000000000000005,
		0.00000000000000000005,
	]
)

/*
const(
	// rounding value
	dec_round = [
		f64(0.44),
		0.044,
		0.0044,
		0.00044,
		0.000044,
		0.0000044,
		0.00000044,
		0.000000044,
		0.0000000044,
		0.00000000044,
		0.000000000044,
		0.0000000000044,
		0.00000000000044,
		0.000000000000044,
		0.0000000000000044,
		0.00000000000000044,
		0.000000000000000044,
		0.0000000000000000044,
		0.00000000000000000044,
		0.000000000000000000044,
	]
)
*/
// max float 1.797693134862315708145274237317043567981e+308

/*
Single format functions
*/
pub struct BF_param {
pub mut:
	pad_ch       byte = byte(` `) // padding char
	len0         int  = -1 // default len for whole the number or string
	len1         int  = 6 // number of decimal digits, if needed
	positive     bool = true // mandatory: the sign of the number passed
	sign_flag    bool       // flag for print sign as prefix in padding
	allign       Align_text = .right // alignment of the string
	rm_tail_zero bool       // remove the tail zeros from floats
}

pub fn format_str(s string, p BF_param) string {
	if p.len0 <= 0 {
		return s.clone()
	}
	dif := p.len0 - utf8_str_visible_length(s)
	if dif <= 0 {
		return s.clone()
	}
	mut res := strings.new_builder(s.len + dif)
	if p.allign == .right {
		for i1 := 0; i1 < dif; i1++ {
			res.write_b(p.pad_ch)
		}
	}
	res.write_string(s)
	if p.allign == .left {
		for i1 := 0; i1 < dif; i1++ {
			res.write_b(p.pad_ch)
		}
	}
	return res.str()
}