KCoreAddons

kformat.h
Go to the documentation of this file.
1/*
2 This file is part of the KDE Frameworks
3
4 SPDX-FileCopyrightText: 2013 Alex Merry <alex.merry@kdemail.net>
5 SPDX-FileCopyrightText: 2013 John Layt <jlayt@kde.org>
6 SPDX-FileCopyrightText: 2010 Michael Leupold <lemma@confuego.org>
7 SPDX-FileCopyrightText: 2009 Michael Pyne <mpyne@kde.org>
8 SPDX-FileCopyrightText: 2008 Albert Astals Cid <aacid@kde.org>
9
10 SPDX-License-Identifier: LGPL-2.0-or-later
11*/
12
13#ifndef KFORMAT_H
14#define KFORMAT_H
15
16#include <kcoreaddons_export.h>
17
18#include <QLocale>
19#include <QSharedPointer>
20#include <QString>
21
22class QDate;
23class QDateTime;
24
25class KFormatPrivate;
26
27/**
28 * \file kformat.h
29 */
30
31/*
32 The code in this class was copied from the old KLocale and modified
33 by John Layt (and also Alex Merry) in the KDELIBS 4 to KDE
34 Frameworks 5 transition in 2013.
35
36 Albert Astals Cid is the original author of formatSpelloutDuration()
37 originally named KLocale::prettyFormatDuration().
38
39 Michael Pyne is the original author of formatByteSize().
40
41 Michael Leupold is the original author of formatRelativeDate(()
42 originally part of KFormat::formatDate().
43*/
44
45/**
46 * @class KFormat kformat.h KFormat
47 *
48 * KFormat provides support for formatting numbers and datetimes in
49 * formats that are not supported by QLocale.
50 *
51 * @author John Layt <jlayt@kde.org>,
52 * Michael Pyne <mpyne@kde.org>,
53 * Albert Astals Cid <aacid@kde.org>,
54 *
55 * @short Class for formatting numbers and datetimes.
56 * @since 5.0
57 */
58class KCOREADDONS_EXPORT KFormat final
59{
60 Q_GADGET
61
62public:
63 /**
64 * These binary units are used in KDE by the formatByteSize()
65 * function.
66 *
67 * NOTE: There are several different units standards:
68 * 1) SI (i.e. metric), powers-of-10.
69 * 2) IEC, powers-of-2, with specific units KiB, MiB, etc.
70 * 3) JEDEC, powers-of-2, used for solid state memory sizing which
71 * is why you see flash cards labels as e.g. 4GB. These (ab)use
72 * the metric units. Although JEDEC only defines KB, MB, GB, if
73 * JEDEC is selected all units will be powers-of-2 with metric
74 * prefixes for clarity in the event of sizes larger than 1024 GB.
75 *
76 * Although 3 different dialects are possible this enum only uses
77 * metric names since adding all 3 different names of essentially the same
78 * unit would be pointless. Use BinaryUnitDialect to control the exact
79 * units returned.
80 *
81 * @see BinaryUnitDialect
82 * @see formatByteSize
83 */
85 /// Auto-choose a unit such that the result is in the range [0, 1000 or 1024)
87
88 // The first real unit must be 0 for the current implementation!
89 UnitByte, ///< B 1 byte
90 UnitKiloByte, ///< KiB/KB/kB 1024/1000 bytes.
91 UnitMegaByte, ///< MiB/MB/MB 2^20/10^06 bytes.
92 UnitGigaByte, ///< GiB/GB/GB 2^30/10^09 bytes.
93 UnitTeraByte, ///< TiB/TB/TB 2^40/10^12 bytes.
94 UnitPetaByte, ///< PiB/PB/PB 2^50/10^15 bytes.
95 UnitExaByte, ///< EiB/EB/EB 2^60/10^18 bytes.
96 UnitZettaByte, ///< ZiB/ZB/ZB 2^70/10^21 bytes.
97 UnitYottaByte, ///< YiB/YB/YB 2^80/10^24 bytes.
98 UnitLastUnit = UnitYottaByte,
99 };
100
101 /**
102 * These units are used in KDE by the formatValue() function.
103 *
104 * @see formatValue
105 * @since 5.49
106 */
107 enum class Unit {
108 Other,
109 Bit, ///< "bit"
110 Byte, ///< "B"
111 Meter, ///< "m"
112 Hertz, ///< "Hz"
113 };
114
115 /**
116 * These prefixes are used in KDE by the formatValue()
117 * function.
118 *
119 * IEC prefixes are only defined for integral units of information, e.g.
120 * bits and bytes.
121 *
122 * @see BinarySizeUnits
123 * @see formatValue
124 * @since 5.49
125 */
126 enum class UnitPrefix {
127 /// Auto-choose a unit such that the result is in the range [0, 1000 or 1024)
129
130 Yocto = 0, ///< --/-/y 10^-24
131 Zepto, ///< --/-/z 10^-21
132 Atto, ///< --/-/a 10^-18
133 Femto, ///< --/-/f 10^-15
134 Pico, ///< --/-/p 10^-12
135 Nano, ///< --/-/n 10^-9
136 Micro, ///< --/-/µ 10^-6
137 Milli, ///< --/-/m 10^-3
138 Centi, ///< --/-/c 0.01
139 Deci, ///< --/-/d 0.1
140 Unity, ///< "" 1
141 Deca, ///< --/-/da 10
142 Hecto, ///< --/-/h 100
143 Kilo, ///< Ki/K/k 1024/1000
144 Mega, ///< Mi/M/M 2^20/10^06
145 Giga, ///< Gi/G/G 2^30/10^09
146 Tera, ///< Ti/T/T 2^40/10^12
147 Peta, ///< Pi/P/P 2^50/10^15
148 Exa, ///< Ei/E/E 2^60/10^18
149 Zetta, ///< Zi/Z/Z 2^70/10^21
150 Yotta, ///< Yi/Y/Y 2^80/10^24
151 };
152
153 /**
154 * This enum chooses what dialect is used for binary units.
155 *
156 * Note: Although JEDEC abuses the metric prefixes and can therefore be
157 * confusing, it has been used to describe *memory* sizes for quite some time
158 * and programs should therefore use either Default, JEDEC, or IEC 60027-2
159 * for memory sizes.
160 *
161 * On the other hand network transmission rates are typically in metric so
162 * Default, Metric, or IEC (which is unambiguous) should be chosen.
163 *
164 * Normally choosing DefaultBinaryDialect is the best option as that uses
165 * the user's selection for units. If the user has not selected a preference,
166 * IECBinaryDialect will typically be used.
167 *
168 * @see BinarySizeUnits
169 * @see formatByteSize
170 */
172 DefaultBinaryDialect = -1, ///< Used if no specific preference
173 IECBinaryDialect, ///< KiB, MiB, etc. 2^(10*n)
174 JEDECBinaryDialect, ///< KB, MB, etc. 2^(10*n)
175 MetricBinaryDialect, ///< SI Units, kB, MB, etc. 10^(3*n)
176 LastBinaryDialect = MetricBinaryDialect,
177 };
178
179 /**
180 * Format flags for formatDuration()
181 * @see DurationFormatOptions
182 */
184 DefaultDuration = 0x0, ///< Default formatting in localized 1:23:45 format
185 InitialDuration = 0x1, ///< Default formatting in localized 1h23m45s format
186 ShowMilliseconds = 0x2, ///< Include milliseconds in format, e.g. 1:23:45.678
187 HideSeconds = 0x4, ///< Hide the seconds, e.g. 1:23 or 1h23m, overrides ShowMilliseconds
188 FoldHours = 0x8, ///< Fold the hours into the minutes, e.g. 83:45 or 83m45s, overrides HideSeconds
189 AbbreviatedDuration = 0x10, ///< Use abbreviated units (e.g. 1 hr 23 min), as a middle ground between just unit initials (InitialDuration) and fully
190 ///< spelled out units (formatSpelloutDuration). Added in 6.11.
191 };
192 /**
193 * Stores a combination of #DurationFormatOption values.
194 */
197
198 /**
199 * Formatting options for formatDistance()
200 */
202 LocaleDistanceUnits = 0x0, ///< Automatically select metric or imperial units based on the current locale
203 MetricDistanceUnits = 0x1, ///< Force the use of metric unites regardless of the current locale
204 };
205 Q_DECLARE_FLAGS(DistanceFormatOptions, DistanceFormatOption)
206 Q_FLAG(DistanceFormatOptions)
207
208 /**
209 * Constructs a KFormat.
210 *
211 * @param locale the locale to use, defaults to the system locale
212 */
213 explicit KFormat(const QLocale &locale = QLocale());
214
215 /**
216 * Copy constructor
217 */
218 KFormat(const KFormat &other);
219
220 KFormat &operator=(const KFormat &other);
221
222 /**
223 * Destructor
224 */
225 ~KFormat();
226
227 /**
228 * Converts @p size from bytes to the appropriate string representation
229 * using the binary unit dialect @p dialect and the specific units @p units.
230 *
231 * Example:
232 * @code
233 * QString metric, iec, jedec, small;
234 * metric = formatByteSize(1000, 1, KFormat::MetricBinaryDialect, KFormat::UnitKiloByte);
235 * iec = formatByteSize(1024, 1, KFormat::IECBinaryDialect, KFormat::UnitKiloByte);
236 * jedec = formatByteSize(1024, 1, KFormat::JEDECBinaryDialect, KFormat::UnitKiloByte);
237 * small = formatByteSize(100);
238 * // metric == "1.0 kB", iec == "1.0 KiB", jedec == "1.0 KB", small == "100 B"
239 * @endcode
240 *
241 * @param size size in bytes
242 * @param precision number of places after the decimal point to use. KDE uses
243 * 1 by default so when in doubt use 1. Whenever KFormat::UnitByte is used
244 * (either explicitly or autoselected from KFormat::DefaultBinaryUnits),
245 * the fractional part is always omitted.
246 * @param dialect binary unit standard to use. Use DefaultBinaryDialect to
247 * use the localized user selection unless you need to use a specific
248 * unit type (such as displaying a flash memory size in JEDEC).
249 * @param units specific unit size to use in result. Use
250 * DefaultBinaryUnits to automatically select a unit that will return
251 * a sanely-sized number.
252 * @return converted size as a translated string including the units.
253 * E.g. "1.23 KiB", "2 GB" (JEDEC), "4.2 kB" (Metric).
254 * @see BinarySizeUnits
255 * @see BinaryUnitDialect
256 */
257
258 QString formatByteSize(double size,
259 int precision = 1,
262
263 /**
264 * Given a number of milliseconds, converts that to a string containing
265 * the localized equivalent, e.g. 1:23:45
266 *
267 * @param msecs Time duration in milliseconds
268 * @param options options to use in the duration format
269 * @return converted duration as a string - e.g. "1:23:45" "1h23m"
270 */
271
272 QString formatDuration(quint64 msecs, KFormat::DurationFormatOptions options = KFormat::DefaultDuration) const;
273
274 /**
275 * Given a number of milliseconds, converts that to a string containing
276 * the localized equivalent to the requested decimal places.
277 *
278 * e.g. given formatDuration(60000), returns "1.0 minutes"
279 *
280 * @param msecs Time duration in milliseconds
281 * @param decimalPlaces Decimal places to round off to, defaults to 2
282 * @return converted duration as a string - e.g. "5.5 seconds" "23.0 minutes"
283 */
284
285 QString formatDecimalDuration(quint64 msecs, int decimalPlaces = 2) const;
286
287 /**
288 * Given a number of milliseconds, converts that to a spell-out string containing
289 * the localized equivalent.
290 *
291 * e.g. given formatSpelloutDuration(60001) returns "1 minute"
292 * given formatSpelloutDuration(62005) returns "1 minute and 2 seconds"
293 * given formatSpelloutDuration(90060000) returns "1 day and 1 hour"
294 *
295 * @param msecs Time duration in milliseconds
296 * @return converted duration as a string.
297 * Units not interesting to the user, for example seconds or minutes when the first
298 * unit is day, are not returned because they are irrelevant. The same applies for
299 * seconds when the first unit is hour.
300 */
301 QString formatSpelloutDuration(quint64 msecs) const;
302
303 /**
304 * Returns a string formatted to a relative date style.
305 *
306 * If the @p date falls within one week before or after the current date
307 * then a relative date string will be returned, such as:
308 * * Yesterday
309 * * Today
310 * * Tomorrow
311 * * Last Tuesday
312 * * Next Wednesday
313 *
314 * If the @p date falls outside this period then the @p format is used.
315 *
316 * @param date the date to be formatted
317 * @param format the date format to use
318 *
319 * @return the date as a string
320 */
321 QString formatRelativeDate(const QDate &date, QLocale::FormatType format) const;
322
323 /**
324 * Returns a string formatted to a relative datetime style.
325 *
326 * If the @p dateTime falls within one week before or after the current date
327 * then a relative date string will be returned, such as:
328 * * Yesterday at 3:00pm
329 * * Today at 3:00pm
330 * * Tomorrow at 3:00pm
331 * * Last Tuesday at 3:00pm
332 * * Next Wednesday at 3:00pm
333 *
334 * If the @p dateTime falls within one hour of the current time.
335 * Then a shorter version is displayed:
336 * * Just a moment ago (for within the same minute)
337 * * 15 minutes ago
338 *
339 * If the @p dateTime falls outside this period then the date is rendered as:
340 * * Monday, 7 September, 2021 at 7:00 PM : date formatted @p format + " at " + time formatted with @p format
341 *
342 * With @p format LongFormat, time format used is set to ShortFormat (to omit timezone and seconds).
343 *
344 * First character is capitalized.
345 *
346 * @param dateTime the date to be formatted
347 * @param format the date format to use
348 *
349 * @return the date as a string
350 */
351 QString formatRelativeDateTime(const QDateTime &dateTime, QLocale::FormatType format) const;
352
353 /**
354 * Converts @p value to the appropriate string representation
355 *
356 * Example:
357 * @code
358 * // sets formatted to "1.0 kbit"
359 * auto formatted = format.formatValue(1000, KFormat::Unit::Bit, 1, KFormat::UnitPrefix::Kilo);
360 * @endcode
361 *
362 * @param value value to be formatted
363 * @param precision number of places after the decimal point to use. KDE uses
364 * 1 by default so when in doubt use 1.
365 * @param unit unit to use in result.
366 * @param prefix specific prefix to use in result. Use UnitPrefix::AutoAdjust
367 * to automatically select an appropriate prefix.
368 * @param dialect prefix standard to use. Use DefaultBinaryDialect to
369 * use the localized user selection unless you need to use a specific
370 * unit type. Only meaningful for KFormat::Unit::Byte, and ignored for
371 * all other units.
372 * @return converted size as a translated string including prefix and unit.
373 * E.g. "1.23 KiB", "2 GB" (JEDEC), "4.2 kB" (Metric), "1.2 kbit".
374 * @see Unit
375 * @see UnitPrefix
376 * @see BinaryUnitDialect
377 * @since 5.49
378 */
379 QString formatValue(double value,
380 KFormat::Unit unit,
381 int precision = 1,
384
385 /**
386 * Converts @p value to the appropriate string representation
387 *
388 * Example:
389 * @code
390 * QString bits, slow, fast;
391 * // sets bits to "1.0 kbit", slow to "1.0 kbit/s" and fast to "12.3 Mbit/s".
392 * bits = format.formatValue(1000, QStringLiteral("bit"), 1, KFormat::UnitPrefix::Kilo);
393 * slow = format.formatValue(1000, QStringLiteral("bit/s");
394 * fast = format.formatValue(12.3e6, QStringLiteral("bit/s");
395 * @endcode
396 *
397 * @param value value to be formatted
398 * @param precision number of places after the decimal point to use. KDE uses
399 * 1 by default so when in doubt use 1.
400 * @param unit unit to use in result.
401 * @param prefix specific prefix to use in result. Use UnitPrefix::AutoAdjust
402 * to automatically select an appropriate prefix.
403 * @return converted size as a translated string including prefix and unit.
404 * E.g. "1.2 kbit", "2.4 kB", "12.3 Mbit/s"
405 * @see UnitPrefix
406 * @since 5.49
407 */
408 // TODO KF7: remove in favor of the method below
409 QString formatValue(double value, const QString &unit, int precision = 1, KFormat::UnitPrefix prefix = KFormat::UnitPrefix::AutoAdjust) const;
410 /**
411 * Converts @p value to the appropriate string representation.
412 *
413 * Example:
414 * @code
415 * QString iec, jedec, metric;
416 * // Sets iec to "1.0 KiB/s", jedec to "1.0 KB/s" and metric to "1.0 kB/s"
417 * iec = format.formatValue(1024, QStringLiteral("B/s"), 1, KFormat::UnitPrefix::AutoAdjust, KFormat::IECBinaryDialect);
418 * jedec = format.formatValue(1024, QStringLiteral("B/s"), 1, KFormat::UnitPrefix::AutoAdjust, KFormat::JEDECBinaryDialect);
419 * metric = format.formatValue(1000, QStringLiteral("B/s"), 1, KFormat::UnitPrefix::AutoAdjust, KFormat::MetricBinaryDialect);
420 * @endcode
421 *
422 * @param value value to be formatted
423 * @param precision number of places after the decimal point to use. 1 is used by default; when
424 * in doubt use 1
425 * @param unit unit to use in result
426 * @param prefix specific prefix to use in result. Use UnitPrefix::AutoAdjust
427 * to automatically select an appropriate prefix
428 * @param dialect prefix standard to use. Use DefaultBinaryDialect to
429 * use the localized user selection unless you need to use a specific
430 * unit type
431 * @return converted size as a translated string including prefix and unit.
432 * E.g. "1.2 kbit", "2.4 kB", "12.3 Mbit/s"
433 * @see UnitPrefix
434 * @since 5.74
435 */
436 QString formatValue(double value, const QString &unit, int precision, KFormat::UnitPrefix prefix, KFormat::BinaryUnitDialect dialect) const;
437
438 /**
439 * Format @p distance given in meters in a suitable unit for displaying.
440 *
441 * For locales using metric units (or when forcing metric units explicitly)
442 * this will use meters and kilometers depending on the distance, for locales
443 * using imperial units this wil use miles and feet.
444 *
445 * @param distance Distance value to be formatted, in meters.
446 * @param options Formatting options.
447 * @return Formatted distance using locale- and distance-appropirate units.
448 *
449 * @since 6.11
450 */
451 [[nodiscard]] QString formatDistance(double distance, KFormat::DistanceFormatOptions = LocaleDistanceUnits) const;
452
453private:
455};
456
457#endif // KFORMAT_H
KFormat provides support for formatting numbers and datetimes in formats that are not supported by QL...
Definition kformat.h:59
DistanceFormatOption
Formatting options for formatDistance()
Definition kformat.h:201
@ LocaleDistanceUnits
Automatically select metric or imperial units based on the current locale.
Definition kformat.h:202
@ MetricDistanceUnits
Force the use of metric unites regardless of the current locale.
Definition kformat.h:203
DurationFormatOption
Format flags for formatDuration()
Definition kformat.h:183
@ ShowMilliseconds
Include milliseconds in format, e.g. 1:23:45.678.
Definition kformat.h:186
@ FoldHours
Fold the hours into the minutes, e.g. 83:45 or 83m45s, overrides HideSeconds.
Definition kformat.h:188
@ HideSeconds
Hide the seconds, e.g. 1:23 or 1h23m, overrides ShowMilliseconds.
Definition kformat.h:187
@ InitialDuration
Default formatting in localized 1h23m45s format.
Definition kformat.h:185
@ AbbreviatedDuration
Use abbreviated units (e.g.
Definition kformat.h:189
@ DefaultDuration
Default formatting in localized 1:23:45 format.
Definition kformat.h:184
QFlags< DurationFormatOption > DurationFormatOptions
Stores a combination of DurationFormatOption values.
Definition kformat.h:195
Unit
These units are used in KDE by the formatValue() function.
Definition kformat.h:107
@ Bit
"bit"
Definition kformat.h:109
@ Hertz
"Hz"
Definition kformat.h:112
KFormat(const QLocale &locale=QLocale())
Constructs a KFormat.
Definition kformat.cpp:14
UnitPrefix
These prefixes are used in KDE by the formatValue() function.
Definition kformat.h:126
@ Milli
–/-/m 10^-3
Definition kformat.h:137
@ Zetta
Zi/Z/Z 2^70/10^21.
Definition kformat.h:149
@ Tera
Ti/T/T 2^40/10^12.
Definition kformat.h:146
@ Kilo
Ki/K/k 1024/1000.
Definition kformat.h:143
@ Peta
Pi/P/P 2^50/10^15.
Definition kformat.h:147
@ Giga
Gi/G/G 2^30/10^09.
Definition kformat.h:145
@ Centi
–/-/c 0.01
Definition kformat.h:138
@ Femto
–/-/f 10^-15
Definition kformat.h:133
@ Atto
–/-/a 10^-18
Definition kformat.h:132
@ Nano
–/-/n 10^-9
Definition kformat.h:135
@ Yotta
Yi/Y/Y 2^80/10^24.
Definition kformat.h:150
@ Exa
Ei/E/E 2^60/10^18.
Definition kformat.h:148
@ Yocto
–/-/y 10^-24
Definition kformat.h:130
@ Deci
–/-/d 0.1
Definition kformat.h:139
@ Hecto
–/-/h 100
Definition kformat.h:142
@ Pico
–/-/p 10^-12
Definition kformat.h:134
@ Zepto
–/-/z 10^-21
Definition kformat.h:131
@ Micro
–/-/µ 10^-6
Definition kformat.h:136
@ AutoAdjust
Auto-choose a unit such that the result is in the range [0, 1000 or 1024)
Definition kformat.h:128
@ Deca
–/-/da 10
Definition kformat.h:141
@ Mega
Mi/M/M 2^20/10^06.
Definition kformat.h:144
BinaryUnitDialect
This enum chooses what dialect is used for binary units.
Definition kformat.h:171
@ JEDECBinaryDialect
KB, MB, etc. 2^(10*n)
Definition kformat.h:174
@ DefaultBinaryDialect
Used if no specific preference.
Definition kformat.h:172
@ IECBinaryDialect
KiB, MiB, etc. 2^(10*n)
Definition kformat.h:173
@ MetricBinaryDialect
SI Units, kB, MB, etc. 10^(3*n)
Definition kformat.h:175
BinarySizeUnits
These binary units are used in KDE by the formatByteSize() function.
Definition kformat.h:84
@ UnitPetaByte
PiB/PB/PB 2^50/10^15 bytes.
Definition kformat.h:94
@ UnitTeraByte
TiB/TB/TB 2^40/10^12 bytes.
Definition kformat.h:93
@ UnitZettaByte
ZiB/ZB/ZB 2^70/10^21 bytes.
Definition kformat.h:96
@ UnitGigaByte
GiB/GB/GB 2^30/10^09 bytes.
Definition kformat.h:92
@ DefaultBinaryUnits
Auto-choose a unit such that the result is in the range [0, 1000 or 1024)
Definition kformat.h:86
@ UnitKiloByte
KiB/KB/kB 1024/1000 bytes.
Definition kformat.h:90
@ UnitYottaByte
YiB/YB/YB 2^80/10^24 bytes.
Definition kformat.h:97
@ UnitMegaByte
MiB/MB/MB 2^20/10^06 bytes.
Definition kformat.h:91
@ UnitByte
B 1 byte.
Definition kformat.h:89
@ UnitExaByte
EiB/EB/EB 2^60/10^18 bytes.
Definition kformat.h:95
This file is part of the KDE documentation.
Documentation copyright © 1996-2025 The KDE developers.
Generated on Fri Jan 24 2025 11:55:52 by doxygen 1.13.2 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.