Home > OS >  Displaying decimal values with a predefined format
Displaying decimal values with a predefined format

Time:01-11

I am getting below sample values from my calculation result and I have to display is in 2 decimal points without rounding it.

-0.00123, -2.222154, -23.154, -2.13, -0.10001, -10.0012, -1.0023, 0.23, 0.56474, 1.000, 11.1111, 1.89566

I am using Decimal Format : 0.00 so,

while using "0.00" , its displaying value for -0.00128 but not displaying for -2.2386

Which should be the proper decimal format as per my need ? I have gone through the documentation here : https://developer.android.com/reference/java/text/DecimalFormat#:~:text=A DecimalFormat comprises a pattern,read from localized ResourceBundle s.

But, Still having confusion so posted question here.

CodePudding user response:

You can use BigDecimal with the desired scale (e.g. 2) and rounding mode (e.g HALF_UP) like so:

import java.math.BigDecimal
import java.math.RoundingMode

fun main() {
    val roundingMode = RoundingMode.HALF_UP
    val doubles: List<Double> = listOf(
        -0.00123, -2.222154, -23.154, -2.13, -0.10001, -10.0012,
        -1.0023, 0.23, 0.56474, 1.000, 11.1111, 1.89566
    )
    doubles.map { BigDecimal(it).setScale(2, roundingMode) }.also { println(it)  }
    // [0.00, -2.22, -23.15, -2.13, -0.10, -10.00, -1.00, 0.23, 0.56, 1.00, 11.11, 1.90]
}

Same approach in a more functional flavour (partial function instead of constants):

val fancyRound: (scale: Int, roundingMode: RoundingMode) -> (Double) -> BigDecimal =
    { scale, roundingMode ->
        { d -> BigDecimal(d).setScale(scale, roundingMode) }
    }

fun main() {
    ...
    val myRound = fancyRound(2, RoundingMode.HALF_UP)
    doubles.map { myRound(it) }.also { println(it) }

}

CodePudding user response:

You could try:

import java.math.RoundingMode;
import java.text.DecimalFormat;

class Scratch {
    public static void main(String[] args) {
        String srcNumber = "-2.2386";
        DecimalFormat formatter = new DecimalFormat("0.00");
        formatter.setRoundingMode(RoundingMode.DOWN);
        srcNumber = formatter.format(Double.valueOf(srcNumber));
        System.out.println(srcNumber);
    }
}
  •  Tags:  
  • Related