Itβs not easy to understand. Rohit Jain mentioned an integer operation. Rounding can also be a problem, since rounding can always be undesirable. I would advise finding an affordable solution, for example, in the triava library.
It can format numbers with arbitrary precision in three different systems (SI, IEC, JEDEC) and various output options. Here are some sample code from triava test blocks :
UnitFormatter.formatAsUnit(1126, UnitSystem.SI, "B"); // = "1.13kB" UnitFormatter.formatAsUnit(2094, UnitSystem.IEC, "B"); // = "2.04KiB"
Print exact kilograms, mega values ββ(here with W = Watt):
UnitFormatter.formatAsUnits(12_000_678, UnitSystem.SI, "W", ", "); // = "12MW, 678W"
You can pass DecimalFormat to customize the output:
UnitFormatter.formatAsUnit(2085, UnitSystem.IEC, "B", new DecimalFormat("0.0000")); // = "2.0361KiB"
For arbitrary operations with kilo or mega values, you can break them into components:
UnitComponent uc = new UnitComponent(123_345_567_789L, UnitSystem.SI); int kilos = uc.kilo();
Christian esken
source share