If you want everything before the dot there is substringBefore():
val temp = main.getString("temp").substringBefore(".") + "°C"
Answer from forpas on Stack OverflowIf you want everything before the dot there is substringBefore():
val temp = main.getString("temp").substringBefore(".") + "°C"
toInt() is solution of your question
val jsonObj = JSONObject(result)
val main = jsonObj.getJSONObject("main")
val temp = +"${main.getString("temp").toDouble().toInt()}°C"
findViewById<TextView>(R.id.temp).text = temp
val x = Math.floor(3.556 * 100) / 100 // == 3.55
Math.floor returns value that less than or equal to the argument and is equal to a mathematical integer.
In our case 3.556 * 100 = 355.6 and the floor would be 355.0, hence 355/100 = 3.55
You can set a rounding mode on the DecimalFormat:
DecimalFormat("#.##")
.apply { roundingMode = RoundingMode.FLOOR }
.format(3.556)
However, note that a Float does not actually store the number in decimal (base 10), and so it is not a suitable format for a number that you need to have a specific number of decimal places. When you convert it to a String, you may find that the number of decimal places has changed. To ensure a specific number of decimal places, you need BigDecimal.
android - How do you remove extra zeros at the end of a decimal in Kotlin? - Stack Overflow
Kotlin calculator can't remove double .0 in the end - Stack Overflow
How do you round a number to N decimal places - Support - Kotlin Discussions
Problem with rounding a number.
Once you have converted the number to a string with up to 2 decimal places (as you are doing), you can use dropLastWhile to drop trailing zeros and decimal places.
Here is an example
fun prettyFormat(input: Double): String {
if( input == 0.0 ) return "0"
val prefix = if( input < 0 ) "-" else ""
val num = abs(input)
// figure out what group of suffixes we are in and scale the number
val pow = floor(log10(num)/3).roundToInt()
val base = num / 10.0.pow(pow * 3)
// Using consistent rounding behavior, always rounding down since you want
// 999999999 to show as 999.99M and not 1B
val roundedDown = floor(base*100)/100.0
// Convert the number to a string with up to 2 decimal places
var baseStr = BigDecimal(roundedDown).setScale(2, RoundingMode.HALF_EVEN).toString()
// Drop trailing zeros, then drop any trailing '.' if present
baseStr = baseStr.dropLastWhile { it == '0' }.dropLastWhile { it == '.' }
val suffixes = listOf("","k","M","B","T")
return when {
pow < suffixes.size -> "$prefix$baseStr${suffixes[pow]}"
else -> "${prefix}infty"
}
}
This produces
11411.0 = 11.41k
11000.0 = 11k
9.99996E8 = 999.99M
12.4 = 12.4
0.0 = 0
-11400.0 = -11.4k
If you don't care about zero or negative numbers it can be simplified a bit.
import java.math.BigDecimal
import java.math.RoundingMode.HALF_EVEN
fun roundBigNumber(number: Long): String {
fun calc(divisor: Long) = BigDecimal(number.toDouble() / divisor)
.setScale(2, HALF_EVEN)
.toString()
.dropLastWhile { it == '0' }
.dropLastWhile { it == '.' }
return when {
number in 1000..999994 -> calc(1000) + "k"
number in 999995..999999 -> "999.99k"
number in 1000000..999994999 -> calc(1000000) + "m"
number in 999995000..999999999 -> "999.99m"
number in 1000000000..999994999999 -> calc(1000000000) + "b"
number in 999995000000..999999999999 -> "999.99b"
number in 1000000000000..999994999999999 -> calc(1000000000000) + "t"
number in 999995000000000..999999999999999 -> "999.99t"
number >= 1000000000000000 -> "∞"
else -> number.toString()
}
}
If I have understood correctly, you wanna get rid of the decimal zeros at the end of a double value (trailing zeros). If so, here is a clean solution. Do all your calculations with double values and when you wanna print the result, do it this way:
resultTextView.text = String.format("%.0f", operand + sec0perand)
this will get rid of the decimal digits if they are zeros or other decimal values (it does not round your number just formats it)
I tried adding .roundToInt() which didn't work, when compiled it gives following error: Type mismatch: inferred type is Int but Double was expected.
You are just doing it in the wrong place, use
resultTextView.text = (operand + sec0perand).roundToInt().toString()
and so on.
I recently started to learn Kotlin. And for now I'm enjoying it. But I wanted to re-create some old tasks from C# because I wanted to get used to Kotlin. But one of the tasks demanded to leave 2 decimal numbers after the dot.
I wonder how can I use Math.round() in order to achive this. Because I personally don't think |"%.2f".Format(value)| it's a reliable way.The picture is me trying to figure it out. Thanks in advance.
Hello, I'm doing kata on codewars and I'm stuck on converting my results to String. The test shows
expected:<[10, 3.0418396189[]]> but was:<[10, 3.0418396189[294032]]>
so, while calculations work fine, it seems I need to cut my answer to 10 decimals before converting it to String. I've tried to use toBigDecimal() but can't understand how to implement it. Documentation says it should be like this
fun Double.toBigDecimal(mathContext: MathContext): BigDecimal
but when I write it as
result.toBigDecimal(MathContext(11, RoundingMode.HALF_UP)).toString()
I get an error 'unresolved reference: MathContext '
Is the way I write this code wrong or I need to import something for this to work, mb there is just better way to do it, any help is appreciated.
Remove last two # after . and add 00 in place of ##.
val dec = DecimalFormat("#,###,##0.00")
Example:
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.*;
public class AddZeroToOneDigitDecimal{
public static void main(String []args){
System.out.println(customFormat(3434));
System.out.println("----------");
System.out.println(customFormat(3434.34));
System.out.println("----------");
System.out.println(customFormat(3434.3));
}
public static String customFormat(double d){
String result = formatter.format(d);
return (result.replace(".00",""));
}
private static DecimalFormat formatter;
private static final String DECIMAL_FORMAT = "#,###,##0.00";
private static DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
static {
formatSymbols.setDecimalSeparator('.');
formatSymbols.setGroupingSeparator(' ');
formatter = new DecimalFormat(DECIMAL_FORMAT, formatSymbols);
}
}
Simplified
val formatter = DecimalFormat("#,###,##0.00");
return formatter.format(value).replace(".00","");