Java Math.signum
Reduce a change in stock to its direction so a dashboard can choose an up or down arrow.
A simple example
Math.signum
- Start with −4
- Do this Read the sign
- Result −1
class Main {
public static void main(String[] args) throws Exception {
System.out.println(Math.signum(-4.0));
}
}
-1.0
Syntax
Math.signum(change)
JDK 21 method signatures (2)
public static double signum(double d)
public static float signum(float f)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaShow the direction of a stock change
A stocktake compares what the scanner found with what the inventory system expected. The report needs to distinguish a shortage, a surplus and an exact match before deciding whether to investigate.
class Main {
public static void main(String[] args) throws Exception {
double change = -12.0;
System.out.printf(java.util.Locale.ROOT, "%.3f%n", (double) (Math.signum(change)));
}
}
-1.000
Removing twelve items gives a direction of minus one. A positive change gives one.
Display a balanced stock count
A closing stocktake finds exactly as many items as the morning ledger predicts. Check how the calculation represents zero change so the report marks neither a shortage nor a surplus.
class Main {
public static void main(String[] args) throws Exception {
double balance = 0.0;
System.out.printf(java.util.Locale.ROOT, "%.3f%n", (double) (Math.signum(balance)));
}
}
0.000
A difference of zero needs a neutral indicator on the dashboard.
Flag a surplus delivery
A store counts five more parcels than expected. Its dashboard displays only the direction of the discrepancy.
Using 5 gives 1 for this measurement.
What to watch for
A result of zero needs its own display state for no change.