How to do calculations with numbers separated with commas? - kotlin

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

Related

How to set Xaxis and Yaxis using data class using kotlin in MpAndroid bar chart

Halo i am trying to create barchart using MPAndroid Library but icant how to use it when i send json from php
echo json_encode($output);
and the output contain 2 data that is hari and total_jual
$rowdata[]=array('hari'=>$row['hari'],
'total_jual'=>$row['total_jual']);
in android studio i am using volley to catch jason
for(i in 0 until arr.length()){
val obj = arr.getJSONObject(i)
dataListPenjualan.add(
ClassPenjualan(
obj.getString("hari").toString(),
obj.getString("total_jual").toString()
)
)
val entries = ArrayList<BarEntry>()
val barDataSet = BarDataSet(entries, "Cells")
val labels = ArrayList<String>()
labels.add(dataListPenjualan[i].hari)
//barDataSet.setColors(ColorTemplate.COLORFUL_COLORS)
barDataSet.color = resources.getColor(R.color.black)
chartPemasukan.animateY(5000)
}
the data i catch using volley i send it into class
this is my class
data class ClassPenjualan (val hari:String,
val totalPenjualan:String)
how can i create barchart using data i catch from php. I already try to search but many explanation is in java.
this is what i try
val entries = ArrayList<BarEntry>()
entries.add(BarEntry(dataListPenjualan[i].hari.toFloat(), i))
val barDataSet = BarDataSet(entries, "Cells")
val labels = ArrayList<String>()
labels.add(dataListPenjualan[i].hari)
val data = BarData(labels, barDataSet)
chartPemasukan.data = data // set the data and list of lables into chart
chartPemasukan.setDescription("Set Bar Chart Description") // set the description
//barDataSet.setColors(ColorTemplate.COLORFUL_COLORS)
barDataSet.color = resources.getColor(R.color.black)
chartPemasukan.animateY(5000)
Your code entries.add(BarEntry(dataListPenjualan[i].hari.toFloat(), i)) is wrong.
just try entries.add(BarEntry(i,dataListPenjualan[i].hari.toFloat()))
below code is my demo
val values = ArrayList<BarEntry>()
var i = 0
while (i < xValueCount) {
val yValue = (Math.random() * (100)).toFloat()
values.add(BarEntry(i.toFloat(), yValue))
i++
}
val set1: BarDataSet
if (chart.data != null &&
chart.data.dataSetCount > 0) {
set1 = chart.data.getDataSetByIndex(0) as BarDataSet
set1.values = values
chart.data.notifyDataChanged()
chart.notifyDataSetChanged()
} else {
set1 = BarDataSet(values, "speed")
//绘制图标
set1.setDrawIcons(false)
//绘制数值
set1.setDrawValues(false)
set1.color = ContextCompat.getColor(mContext, getBarHighColorByDataType(false))
set1.highLightColor = ContextCompat.getColor(mContext, getBarHighColorByDataType(true))
set1.highLightAlpha = 255
val dataSets = ArrayList<IBarDataSet>()
dataSets.add(set1)
val data = BarData(dataSets)
data.setValueTextSize(10f)
//barWith = 柱宽度/(柱宽度+旁边一处空白宽度)
data.barWidth = when (dataType) {
0 -> 0.37f
1 -> 0.52f
2 -> 0.3f
else -> 0.43f
}
chart.data = data
}

Regex and .contains

I am recognizing words from an Imageview using FirbaseVisionImage class. I want to determined a substring which has a regex pattern of ( "^\\d{6}-\\d{2}-\\d{4}\$") from the whole string from an Imageview, and then show the substring which has the regex pattern of ( "^\\d{6}-\\d{2}-\\d{4}\$") at a textview, however it won't work
val rotatedBitmap = rotateBitmap(bitmap, 270f)
val firebaseVisionImage = FirebaseVisionImage.fromBitmap(rotatedBitmap)
val firebaseVision = FirebaseVision.getInstance()
val firebaseVisionTextRecognizer = firebaseVision.onDeviceTextRecognizer
val task: Task<FirebaseVisionText> =
firebaseVisionTextRecognizer.processImage(firebaseVisionImage)
task.addOnSuccessListener { p0 ->
var s = p0?.text
val regex = Regex( "^\\d{6}-\\d{2}-\\d{4}\$")
var icFormat = ""
var subString = regex.matches(icFormat)
if(s!!.contains(subString.toString())){
binding.tvDemo.text = subString.toString()
}else{
binding.tvDemo.text = "Cannot Detect Regex"
}
}

Kotlin - The caracter literal does not conform expect type Int

I'm struggling with types with my program, I've been asked to do it in JS first and it worked fine but now I can't achieve the result.
Do you think I should make another 'algorithm' ? In advance, thank you for your time.
fun main(){
// the idea is to put numbers in a box
// that cant be larger than 10
val data = "12493419133"
var result = data[0]
var currentBox = Character.getNumericValue(data[0])
var i = 1
while(i < data.length){
val currentArticle = Character.getNumericValue(data[i])
currentBox += currentArticle
println(currentBox)
if(currentBox <= 10){
result += Character.getNumericValue(currentArticle)
}else{
result += '/'
//var resultChar = result.toChar()
// result += '/'
currentBox = Character.getNumericValue(currentArticle)
result += currentArticle
}
i++
}
print(result) //should print 124/9/341/91/33
}
The result is actually of a Char type, and the overload operator function + only accepts Int to increment ASCII value to get new Char.
public operator fun plus(other: Int): Char
In idomatic Kotlin way, you can solve your problem:
fun main() {
val data = "12493419133"
var counter = 0
val result = data.asSequence()
.map(Character::getNumericValue)
.map { c ->
counter += c
if (counter <= 10) c.toString() else "/$c".also{ counter = c }
}
.joinToString("") // terminal operation, will trigger the map functions
println(result)
}
Edit: If the data is too large, you may want to use StringBuilder because it doesn't create string every single time the character is iterated, and instead of using a counter of yourself you can use list.fold()
fun main() {
val data = "12493419133"
val sb = StringBuilder()
data.fold(0) { acc, c ->
val num = Character.getNumericValue(c)
val count = num + acc
val ret = if (count > 10) num.also { sb.append('/') } else count
ret.also { sb.append(c) } // `ret` returned to ^fold, next time will be passed as acc
}
println(sb.toString())
}
If you want a result in List<Char> type:
val data = "12493419133"
val result = mutableListOf<Char>()
var sum = 0
data.asSequence().forEach {
val v = Character.getNumericValue(it)
sum += v
if (sum > 10) {
result.add('/')
sum = v
}
result.add(it)
}
println(result.joinToString(""))

How to get length of a character array in kotlin?

I am trying to find the length of two different character array but I am only being allowed to use array.size only once.
How to bypass this problem?
fun chararraytostr(inp1: CharArray): String{
var arlen: Int = inp1.size //here lies the problem
var out1: String = ""
for(j in 0..arlen-1){
var str = inp1[j].toString()
out1+=str
}
return out1
}
fun uppercase(input: String): String{
var temp1: CharArray = input.toCharArray()
var len = input.size //here lies the problem
var temp3: Char
for(i in 0..len-1){
var temp2: Char = temp1[i]
var ascii: Int = temp2.toInt()
if(ascii<=122 && ascii>=97){
ascii-=32
temp3 = ascii.toChar()
temp1[i] = temp3
}else{}
}
var output = chararraytostr(temp1)
return output
}
fun main(arg: Array<String>){
var toupper = "Hi my friend!"
println(uppercase(toupper))
}
It is always showing Unresolved reference: size. I don't know why. Please help.
You're calling size on the String variable instead of the CharArray variable. Use temp1.size instead of input.size.

kotlin SQLite database always writing default values, never new ones

here is the class I set up for my database. database handler being the inner class.
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.content.ContentValues
import android.util.Log
import java.sql.Date
class Scores {
var id : Int = 0
var dataBaseName = "ScoreDatabase"
var averageTime = 0.0f
val date = Date(System.currentTimeMillis()).toString()
constructor(averageTime:Float) {
this.averageTime = averageTime
Log.d("Poop", averageTime.toString())
}
constructor()
inner class DataBaseHandler(var context:Context, tableName:String): SQLiteOpenHelper(context, dataBaseName, null,1){
val TABLE_NAME = tableName
val COL_ID = "id"
val COL_AVG = "Average_Time"
val COL_DATE = "Date"
override fun onCreate(db: SQLiteDatabase?) {
val createTable = "CREATE TABLE " + TABLE_NAME +" (" +
COL_ID +" INTEGER PRIMARY KEY AUTOINCREMENT," +
COL_AVG + " VARCHAR(256)," +
COL_DATE +" VARCHAR(256)"
db?.execSQL(createTable)
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
fun insertData(score: Scores){
val db = this.writableDatabase
var cv = ContentValues()
cv.put(COL_AVG,score.averageTime)
cv.put(COL_DATE,score.date)
var result = db.insert(TABLE_NAME,null,cv)
if(result == -1.toLong())
Log.d("POOP", "fail score table in addition")
else
Log.d("POOP", "Success score table in addition" )
}
fun readData(): MutableList<Scores>{
var list: MutableList<Scores> = ArrayList()
val db = this.readableDatabase
val query = "Select * from $TABLE_NAME"
val result = db.rawQuery(query,null)
if (result.moveToFirst()){
do {
var score = Scores()
var id = result.getString(0).toInt()
var AvgTime = result.getString(1).toFloat()
var date = result.getString(2).toString()
list.add(score)
}while (result.moveToNext())
}
result.close()
db.close()
return list
}
}
}
I tried this where the scores class and the handler were two separate classes, but it generated the same results.
here is how I write to the database (from 4 separate activities. in each activity the tablename is different. in this one for example it is 'additionDataBase')
val scores = Scores("%.3f".format(timeKeeper.averageNumber).toFloat())
val db = scores.DataBaseHandler(context, "additionDataBase")
db.insertData(scores)
and here is how I read from the database which is in a different activity that shows the averageTime from each table. here is the code for one of them
val context: Context? = activity
val adb = Scores().DataBaseHandler(context!!,"additionDataBase")
val data = adb.readData()
TextViewAdScore.text = data[0].averageTime.toString() + " " + data[1].date
I think I am missing something, but I can't seem to find what it is.
so far, no matter how many times I do this. the output is always 0.0f
Look at what you do in readData:
var score = Scores()
var id = result.getString(0).toInt()
var AvgTime = result.getString(1).toFloat()
var date = result.getString(2).toString()
list.add(score)
id, AvgTime, and date are retrieved but not used in any way, so your code is equivalent to just writing list.add(Scores()). (Side note: there's no reason for them to be var, and why the case inconsistency between AvgTime and the rest?)