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). @since 6.11.
191 };
192 /**
193 * Stores a combination of #DurationFormatOption values.
194 */
197
198 /**
199 * Formatting options for formatDistance()
200 *
201 * @since 6.11
202 */
204 LocaleDistanceUnits = 0x0, ///< Automatically select metric or imperial units based on the current locale
205 MetricDistanceUnits = 0x1, ///< Force the use of metric unites regardless of the current locale
206 };
207 Q_DECLARE_FLAGS(DistanceFormatOptions, DistanceFormatOption)
208 Q_FLAG(DistanceFormatOptions)
209
210 /**
211 * Constructs a KFormat.
212 *
213 * @param locale the locale to use, defaults to the system locale
214 */
215 explicit KFormat(const QLocale &locale = QLocale());
216
217 /**
218 * Copy constructor
219 */
220 KFormat(const KFormat &other);
221
222 KFormat &operator=(const KFormat &other);
223
224 /**
225 * Destructor
226 */
227 ~KFormat();
228
229 /**
230 * Converts @p size from bytes to the appropriate string representation
231 * using the binary unit dialect @p dialect and the specific units @p units.
232 *
233 * Example:
234 * @code
235 * QString metric, iec, jedec, small;
236 * metric = formatByteSize(1000, 1, KFormat::MetricBinaryDialect, KFormat::UnitKiloByte);
237 * iec = formatByteSize(1024, 1, KFormat::IECBinaryDialect, KFormat::UnitKiloByte);
238 * jedec = formatByteSize(1024, 1, KFormat::JEDECBinaryDialect, KFormat::UnitKiloByte);
239 * small = formatByteSize(100);
240 * // metric == "1.0 kB", iec == "1.0 KiB", jedec == "1.0 KB", small == "100 B"
241 * @endcode
242 *
243 * @param size size in bytes
244 * @param precision number of places after the decimal point to use. KDE uses
245 * 1 by default so when in doubt use 1. Whenever KFormat::UnitByte is used
246 * (either explicitly or autoselected from KFormat::DefaultBinaryUnits),
247 * the fractional part is always omitted.
248 * @param dialect binary unit standard to use. Use DefaultBinaryDialect to
249 * use the localized user selection unless you need to use a specific
250 * unit type (such as displaying a flash memory size in JEDEC).
251 * @param units specific unit size to use in result. Use
252 * DefaultBinaryUnits to automatically select a unit that will return
253 * a sanely-sized number.
254 * @return converted size as a translated string including the units.
255 * E.g. "1.23 KiB", "2 GB" (JEDEC), "4.2 kB" (Metric).
256 * @see BinarySizeUnits
257 * @see BinaryUnitDialect
258 */
259
260 QString formatByteSize(double size,
261 int precision = 1,
264
265 /**
266 * Given a number of milliseconds, converts that to a string containing
267 * the localized equivalent, e.g. 1:23:45
268 *
269 * @param msecs Time duration in milliseconds
270 * @param options options to use in the duration format
271 * @return converted duration as a string - e.g. "1:23:45" "1h23m"
272 */
273
274 QString formatDuration(quint64 msecs, KFormat::DurationFormatOptions options = KFormat::DefaultDuration) const;
275
276 /**
277 * Given a number of milliseconds, converts that to a string containing
278 * the localized equivalent to the requested decimal places.
279 *
280 * e.g. given formatDuration(60000), returns "1.0 minutes"
281 *
282 * @param msecs Time duration in milliseconds
283 * @param decimalPlaces Decimal places to round off to, defaults to 2
284 * @return converted duration as a string - e.g. "5.5 seconds" "23.0 minutes"
285 */
286
287 QString formatDecimalDuration(quint64 msecs, int decimalPlaces = 2) const;
288
289 /**
290 * Given a number of milliseconds, converts that to a spell-out string containing
291 * the localized equivalent.
292 *
293 * e.g. given formatSpelloutDuration(60001) returns "1 minute"
294 * given formatSpelloutDuration(62005) returns "1 minute and 2 seconds"
295 * given formatSpelloutDuration(90060000) returns "1 day and 1 hour"
296 *
297 * @param msecs Time duration in milliseconds
298 * @return converted duration as a string.
299 * Units not interesting to the user, for example seconds or minutes when the first
300 * unit is day, are not returned because they are irrelevant. The same applies for
301 * seconds when the first unit is hour.
302 */
303 QString formatSpelloutDuration(quint64 msecs) const;
304
305 /**
306 * Returns a string formatted to a relative date style.
307 *
308 * If the @p date falls within one week before or after the current date
309 * then a relative date string will be returned, such as:
310 * * Yesterday
311 * * Today
312 * * Tomorrow
313 * * Last Tuesday
314 * * Next Wednesday
315 *
316 * If the @p date falls outside this period then the @p format is used.
317 *
318 * @param date the date to be formatted
319 * @param format the date format to use
320 *
321 * @return the date as a string
322 */
323 QString formatRelativeDate(const QDate &date, QLocale::FormatType format) const;
324
325 /**
326 * Returns a string formatted to a relative datetime style.
327 *
328 * If the @p dateTime falls within one week before or after the current date
329 * then a relative date string will be returned, such as:
330 * * Yesterday at 3:00pm
331 * * Today at 3:00pm
332 * * Tomorrow at 3:00pm
333 * * Last Tuesday at 3:00pm
334 * * Next Wednesday at 3:00pm
335 *
336 * If the @p dateTime falls within one hour of the current time.
337 * Then a shorter version is displayed:
338 * * Just a moment ago (for within the same minute)
339 * * 15 minutes ago
340 *
341 * If the @p dateTime falls outside this period then the date is rendered as:
342 * * Monday, 7 September, 2021 at 7:00 PM : date formatted @p format + " at " + time formatted with @p format
343 *
344 * With @p format LongFormat, time format used is set to ShortFormat (to omit timezone and seconds).
345 *
346 * First character is capitalized.
347 *
348 * @param dateTime the date to be formatted
349 * @param format the date format to use
350 *
351 * @return the date as a string
352 */
353 QString formatRelativeDateTime(const QDateTime &dateTime, QLocale::FormatType format) const;
354
355 /**
356 * Converts @p value to the appropriate string representation
357 *
358 * Example:
359 * @code
360 * // sets formatted to "1.0 kbit"
361 * auto formatted = format.formatValue(1000, KFormat::Unit::Bit, 1, KFormat::UnitPrefix::Kilo);
362 * @endcode
363 *
364 * @param value value to be formatted
365 * @param precision number of places after the decimal point to use. KDE uses
366 * 1 by default so when in doubt use 1.
367 * @param unit unit to use in result.
368 * @param prefix specific prefix to use in result. Use UnitPrefix::AutoAdjust
369 * to automatically select an appropriate prefix.
370 * @param dialect prefix standard to use. Use DefaultBinaryDialect to
371 * use the localized user selection unless you need to use a specific
372 * unit type. Only meaningful for KFormat::Unit::Byte, and ignored for
373 * all other units.
374 * @return converted size as a translated string including prefix and unit.
375 * E.g. "1.23 KiB", "2 GB" (JEDEC), "4.2 kB" (Metric), "1.2 kbit".
376 * @see Unit
377 * @see UnitPrefix
378 * @see BinaryUnitDialect
379 * @since 5.49
380 */
381 QString formatValue(double value,
382 KFormat::Unit unit,
383 int precision = 1,
386
387 /**
388 * Converts @p value to the appropriate string representation
389 *
390 * Example:
391 * @code
392 * QString bits, slow, fast;
393 * // sets bits to "1.0 kbit", slow to "1.0 kbit/s" and fast to "12.3 Mbit/s".
394 * bits = format.formatValue(1000, QStringLiteral("bit"), 1, KFormat::UnitPrefix::Kilo);
395 * slow = format.formatValue(1000, QStringLiteral("bit/s");
396 * fast = format.formatValue(12.3e6, QStringLiteral("bit/s");
397 * @endcode
398 *
399 * @param value value to be formatted
400 * @param precision number of places after the decimal point to use. KDE uses
401 * 1 by default so when in doubt use 1.
402 * @param unit unit to use in result.
403 * @param prefix specific prefix to use in result. Use UnitPrefix::AutoAdjust
404 * to automatically select an appropriate prefix.
405 * @return converted size as a translated string including prefix and unit.
406 * E.g. "1.2 kbit", "2.4 kB", "12.3 Mbit/s"
407 * @see UnitPrefix
408 * @since 5.49
409 */
410 // TODO KF7: remove in favor of the method below
411 QString formatValue(double value, const QString &unit, int precision = 1, KFormat::UnitPrefix prefix = KFormat::UnitPrefix::AutoAdjust) const;
412 /**
413 * Converts @p value to the appropriate string representation.
414 *
415 * Example:
416 * @code
417 * QString iec, jedec, metric;
418 * // Sets iec to "1.0 KiB/s", jedec to "1.0 KB/s" and metric to "1.0 kB/s"
419 * iec = format.formatValue(1024, QStringLiteral("B/s"), 1, KFormat::UnitPrefix::AutoAdjust, KFormat::IECBinaryDialect);
420 * jedec = format.formatValue(1024, QStringLiteral("B/s"), 1, KFormat::UnitPrefix::AutoAdjust, KFormat::JEDECBinaryDialect);
421 * metric = format.formatValue(1000, QStringLiteral("B/s"), 1, KFormat::UnitPrefix::AutoAdjust, KFormat::MetricBinaryDialect);
422 * @endcode
423 *
424 * @param value value to be formatted
425 * @param precision number of places after the decimal point to use. 1 is used by default; when
426 * in doubt use 1
427 * @param unit unit to use in result
428 * @param prefix specific prefix to use in result. Use UnitPrefix::AutoAdjust
429 * to automatically select an appropriate prefix
430 * @param dialect prefix standard to use. Use DefaultBinaryDialect to
431 * use the localized user selection unless you need to use a specific
432 * unit type
433 * @return converted size as a translated string including prefix and unit.
434 * E.g. "1.2 kbit", "2.4 kB", "12.3 Mbit/s"
435 * @see UnitPrefix
436 * @since 5.74
437 */
438 QString formatValue(double value, const QString &unit, int precision, KFormat::UnitPrefix prefix, KFormat::BinaryUnitDialect dialect) const;
439
440 /**
441 * Format @p distance given in meters in a suitable unit for displaying.
442 *
443 * For locales using metric units (or when forcing metric units explicitly)
444 * this will use meters and kilometers depending on the distance, for locales
445 * using imperial units this wil use miles and feet.
446 *
447 * @param distance Distance value to be formatted, in meters.
448 * @param options Formatting options.
449 * @return Formatted distance using locale- and distance-appropirate units.
450 *
451 * @since 6.11
452 */
453 [[nodiscard]] QString formatDistance(double distance, KFormat::DistanceFormatOptions = LocaleDistanceUnits) const;
454
455private:
457};
458
459#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:203
@ LocaleDistanceUnits
Automatically select metric or imperial units based on the current locale.
Definition kformat.h:204
@ MetricDistanceUnits
Force the use of metric unites regardless of the current locale.
Definition kformat.h:205
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 Feb 28 2025 12:00:49 by doxygen 1.13.2 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.