string - Automatically format a measurement into engineering units in Java -
i'm trying find way automatically format measurement , unit string in engineering notation. special case of scientific notation, in exponent multiple of three, denoted using kilo, mega, milli, micro prefixes.
this similar this post except should handle whole range of si units , prefixes.
for example, i'm after library format quantities such that: 12345.6789 hz formatted 12 khz or 12.346 khz or 12.3456789 khz 1234567.89 j formatted 1 mj or 1.23 mj or 1.2345 mj , on.
jsr-275 / jscience handle unit measurement ok, i'm yet find work out appropriate scaling prefix automatically based on magnitude of measurement.
cheers, sam.
import java.util.*; class measurement { public static final map<integer,string> prefixes; static { map<integer,string> tempprefixes = new hashmap<integer,string>(); tempprefixes.put(0,""); tempprefixes.put(3,"k"); tempprefixes.put(6,"m"); tempprefixes.put(9,"g"); tempprefixes.put(12,"t"); tempprefixes.put(-3,"m"); tempprefixes.put(-6,"u"); prefixes = collections.unmodifiablemap(tempprefixes); } string type; double value; public measurement(double value, string type) { this.value = value; this.type = type; } public string tostring() { double tval = value; int order = 0; while(tval > 1000.0) { tval /= 1000.0; order += 3; } while(tval < 1.0) { tval *= 1000.0; order -= 3; } return tval + prefixes.get(order) + type; } public static void main(string[] args) { measurement dist = new measurement(1337,"m"); // should 1.337km measurement freq = new measurement(12345678,"hz"); // should 12.3mhz measurement tiny = new measurement(0.00034,"m"); // should 0.34mm system.out.println(dist); system.out.println(freq); system.out.println(tiny); } }
Comments
Post a Comment