Home > Software engineering >  How to do calculations with numbers separated with commas?
How to do calculations with numbers separated with commas?

Time:01-15

I want to do calculations with numbers separated by thousands (comma), and the result will be formatted in thousands separated (comma) as well. Example:

var editText1 = **12,520.00**
var editText2 = **52,345.00**
var result = **64,825.00**
//
var editText1 = **12,520**
var editText2 = **52,345**
var result = **64,825.00**

=====================================

I just tried to format the result according to the separation in thousands (comma) of the values that I would receive.

//formats
decimalSymbols = DecimalFormatSymbols(Locale.US)
format="##,###.##"
decimal = DecimalFormat(format, decimalSymbols)
decimal.roundingMode = RoundingMode.CEILING

//Variables that will receive the values
val prov = profit.text.toString().toDouble()
val cust = costs.text.toString().toDouble()
val amort = amortizacoes.text.toString().toDouble()
val jur = interest.text.toString().toDouble()

//Formatting the result in BigDecimal
result val = (prov - cost - amort - jur) * 0.32
val parsed = BigDecimal(result)
val formatResult = decimal.format(parsed)

tax.setText(formatResult.toString())

CodePudding user response:

  • Simply remove all commas from the string value:

    value= value.replace(",", "")
    
  • Do your calculations

  • And finally, you can use format to decorate and show them with commas, with:

    "%,d".format(value)
    

Tested with JVM and Kotlin v1.8.0.

Here is the playground link: enter image description here

Code snippet, pasted here:

fun main() {

    var editText1 = "12,520.00";
    var editText2 = "52,345.00";
// var result = **64,825.00**
    editText1 = editText1.replace(",","");
    editText2 = editText2.replace(",","");
    
    var resDouble = editText1.toDouble() * editText2.toDouble();
    val res = "%,f".format(resDouble)
    println(res)
}
  • Related