简体   繁体   中英

How to do calculations with numbers separated with commas?

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())
  • 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: https://pl.kotl.in/pXpev-dei

在此处输入图像描述

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM