how to round 47.3476 to 47.35 in kotlin
val num = 47.3476
val df = DecimalFormat("#.##")//set decimal format here
df.roundingMode = RoundingMode.CEILING
println(df.format(num)) //47.35
Related
I wish to sum up two numbers. They are BigDecimals.
n1 = 0.0000000040.toBigDecimal()
n2 = 0.0000000030.toBigDecimal()
println(n1 + n2) //result: 7.0E-9
How can I fix it to get the result 0.0000000070 as BigDecimal?
Try
println((n1 + n2).toPlainString())
You can use string format to have the desired output.
val n1 = 0.0000000040.toBigDecimal()
val n2 = 0.0000000030.toBigDecimal()
// addition of BigDecimals
val n3 = n1 + n2
val n4 = n1.add(n2)
// "Returns a string representation of this BigDecimal without an exponent field."
println(n4.toPlainString())
// formatted output
val n3output = String.format("%.10f", n3)
println(n3output)
I'm trying to pick the dominant color from a bitmap using Palette:
val p: Palette = Palette.from(bitmap!!).generate()
Log.d(TAG, "${p.getDominantColor(0)}")
And the output is -8341352
From reference the value returned is a RGB packet int. So how can I get the real information of color? I can't find the comparison to an RGB value from a negative integer with seven-digit
Use the Color utility functions to extract the RGBA components of the color as integers in the range 0-255 inclusive.
val argb = p.getDominantColor(0)
val a = Color.alpha(argb)
val r = Color.red(argb)
val g = Color.green(argb)
val b = Color.blue(argb)
If you're using androidx core-ktx library (default projects probably already are), you can get them by destructuring:
val (a, r, g, b) = p.getDominantColor(0)
If you want the values as floats in the range 0..1, you can divide the above values by 255f, or if your min SDK version is at least 26 you can use destructuring like this (note A is last instead of first when working with the Color class rather than an Int that represents a color):
val argb = p.getDominantColor(0)
val (r, g, b, a) = Color.valueOf(argb)
In the following Kotlin code example I expected the value of parameter i to be equal to 0, such as is the case for the parameter k. The IDE reports all i, j and k as Int. Is it a bug or do I need to readjust my understanding of Kotlin casting inside expressions? For example, is there a rule to always promote/cast to Double inside expressions involving division, but not multiplication?
fun main() {
//Kotlin 1.3.61
val x = 100 * 1.0/100 //Double
val i = 100 * 1/100 //Int
val j = 1/100 //Int
val k = 100 * j //Int
println(x) //1.0
println(i) //1
println(j) //0
println(k) //0
}
I expected the value of parameter i to be equal to 0
The output is arithmetically right: 100 * 1 / 100 = (100 * 1) / 100 = 100 / 100 = 1 / 1 = 1
, such as is the case for the parameter k.
The value j is 0, so anything multiplied by it will be zero, as in case of k.
is there a rule to always promote/cast to Double inside expressions
involving division, but not multiplication?
If you divide integers, you will get an integer back. If one of the numbers is a Double, the result will be a Double:
val x = 100 * 1.0/100 //Double because 1.0 is a Double
--
There is actually already a discussion on kotlin forum to your problem here:
Mathematically speaking the current behaviour is correct.
This is called integer devision and results in the quotient as an
answer
I have a dataframe that has colum of datatype DecimalType(38,10). Not all values have 10 decimal digits. I want to select those rows that have a scale bigger than 4 (after removing the trailing zeros).
Is there a way to do that?
In pseudo code something like ds.select(col1, col2).where(col3.hasScale >4)
Something like this could do it:
import org.apache.spark.sql.Row;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
import org.apache.spark.sql.types.StringType;
import org.apache.spark.sql.types.DataTypes;
val maxScale = 10
val decimalType = DataTypes.createDecimalType(38, maxScale)
val data = Seq(
Row(BigDecimal.decimal(3.302302)),
Row(BigDecimal.decimal(3.4434)),
Row(BigDecimal.decimal(4.32)),
Row(BigDecimal.decimal(4.230240505)),
Row(BigDecimal.decimal(7.302)),
Row(BigDecimal.decimal(4.34444))
)
val schema = List(
StructField("number", decimalType, true)
)
val df = spark.createDataFrame(
spark.sparkContext.parallelize(data),
StructType(schema)
)
df.show()
val decimalScale = udf((n: Double) => {
Stream.range(0, maxScale + 1).map { s =>
val multiplier = scala.math.pow(10, maxScale)
val modulus = scala.math.pow(10, maxScale - s)
(s, n * multiplier % modulus)
}.find(_._2 == 0).get._1
})
df.filter(decimalScale(col("number")) > 4).show()
I've been trying out swift lately and i've come across a rather simple Problem.
In Obj-C when i want to get the fraction digits of a float i'd do the following:
float x = 3.141516
int integer_x = (int)x;
float fractional_x = x-integer_x;
//Result: fractional_x = 0.141516
in Swift:
let x:Float = 3.141516
let integerX:Int = Int(x)
let fractionalX:Float = x - integerX
-> this results in an error because of mismachting types
Any Idea how to do it correctly?
Thanks in Advance
Malte
Use the modf function:
let v = 3.141516
var integer = 0.0
let fraction = modf(v, &integer)
println("fraction: \(fraction)");
output:
fraction: 0.141516
For float instead of double just use: modff
Use .truncatingRemainder(dividingBy:) which replaced the modulo operator (x % 1), which (for modulo)
immediately (it is only one character), and
with few cpu cycles (presumably only one cycle, since modulo is a common cpu instruction)
gives the fractional part.
let x:Float = 3.141516
let fracPart = x.truncatingRemainder(dividingBy: 1) // fracPart is now 0.141516
fracPart will assume the value: 0.141516. This works for double and float.
The problem is that you cannot subtract Float and Int, you should convert one of this value to be the same as another, try that:
let fractionalX:Float = x - Float(integerX)
Swift 3 does not like the modulus operator %. It wants me to use truncatingRemainder of Double type.
let x1:Double = 123.00
let t1 = x1.truncatingRemainder(dividingBy: 1)
print("t1 = \(t1)")
let x2:Double = 123.45
let t2 = x2.truncatingRemainder(dividingBy: 1)
print("t2 = \(t2)")
Produces output:
t1 = 0.0
t2 = 0.450000000000003
To remove the 3 quadrillionth artifact you should probably round the result.
Why using an int whatsoever?
What about this instead:
import Darwin
let x = 3.1415926
let xf = x - (x > 0 ? floor(x) : ceil(x))
It will use doubles by default here. Feel free to use floats if it's what you need:
let x: Float = 3.1415926
Is that what you are looking for?