Formatting decimal places with unknown number
A Float
uses a binary (IEEE 754) representation and cannot represent
all decimal fractions precisely. For example,
let x : Float = 123.456
stores in x
the bytes 42f6e979
, which is approximately 123.45600128173828
. So does x
have 3 or 14 fractional digits?
You can use NSNumberFormatter
if you specify a maximum number
of decimal digits that should be presented:
let fmt = NSNumberFormatter()
fmt.locale = NSLocale(localeIdentifier: "en_US_POSIX")
fmt.maximumFractionDigits = 3
fmt.minimumFractionDigits = 0
println(fmt.stringFromNumber(123)!) // 123
println(fmt.stringFromNumber(123.4)!) // 123.4
println(fmt.stringFromNumber(123.45)!) // 123.45
println(fmt.stringFromNumber(123.456)!) // 123.456
println(fmt.stringFromNumber(123.4567)!) // 123.457
Swift 3/4 update:
let fmt = NumberFormatter()
fmt.locale = Locale(identifier: "en_US_POSIX")
fmt.maximumFractionDigits = 3
fmt.minimumFractionDigits = 0
print(fmt.string(for: 123.456)!) // 123.456
MySQL format number with unknown number of decimal places
As suggested split the string drop the trailing zeros format the number before the decimal point and concat taking into account the possibility of no decimals being present at all for example
set @a = 1234.56;
select
case when instr(@a,'.') > 0 then
concat(
format(substring_index(@a,'.',1),'###,###,###'),
'.',
trim(trailing '0' from substring_index(@a,'.',-1))
)
else
format (@a,'###,###,###')
end formatted
How to nicely format floating numbers to string without unnecessary decimal 0's
If the idea is to print integers stored as doubles as if they are integers, and otherwise print the doubles with the minimum necessary precision:
public static String fmt(double d)
{
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}
Produces:
232
0.18
1237875192
4.58
0
1.2345
And does not rely on string manipulation.
Creating a decimal number with no decimal separator
Why would you use your own pattern? Java default implementation has pretty good patterns in most of locales. At least by looking Oracle's docs it looks that it should do what you need to:
Locale Formatted Numbers
German (Germany) 123.456,789
German (Switzerland) 123'456.789
English (United States) 123,456.789
So what you have to do ( besides dividing a number by 100 ) is set minimum fraction digits to "2":
public static String formatDecimal(double number) {
NumberFormat german = NumberFormat.getNumberInstance(Locale.GERMAN);
german.setMinimumFractionDigits(2);
return german.format(number / 100);
}
Edited: prints numbers as expected:
0,00
0,01
0,02
0,09
0,10
0,11
0,99
1,00
1,01
9,99
10,00
10,01
99,99
100,00
100,01
999,99
1.000,00
1.000,01
9.999,99
10.000,00
10.000,01
99.999,99
100.000,00
100.000,01
999.999,99
1.000.000,00
1.000.000,01
Use DecimalFormat to get varying amount of decimal places
Create a method to generate a certain number of #
to a string, like so:
public static String generateNumberSigns(int n) {
String s = "";
for (int i = 0; i < n; i++) {
s += "#";
}
return s;
}
And then use that method to generate a string to pass to the DecimalFormat
class:
double value = 1234.567890;
int numPlaces = 5;
String numberSigns = generateNumberSigns(numPlaces);
DecimalFormat fmt = new DecimalFormat ("0." + numberSigns);
System.out.println(fmt.format(value));
OR simply do it all at once without a method:
double value = 1234.567890;
int numPlaces = 5;
String numberSigns = "";
for (int i = 0; i < numPlaces; i++) {
numberSigns += "#";
}
DecimalFormat fmt = new DecimalFormat ("0." + numberSigns);
System.out.println(fmt.format(value));
Formatting decimal places in a character column. as.numeric erase the values in the column
I assume you are somewhere which uses a comma for a decimal point, and perhaps a decimal point in place of a thousands separator.
As an example:
df <- c(',958229561278528615818098193915712388824', '2,05561009284393218251509777394193942492', '2,72096803821411321343605598060792704404', '2,00324997757400185789440370684992098409')
First, remove any decimal points, because they may be thousands separators. Then, replace the comma with a decimal point:
as.numeric(gsub(',', '.', gsub('\\.', '', df)))
Edit: however, if you intend to use more than the first few decimal places, you may run into problems with precision. Look into the package Rmpfr if you need arbitrary precision.
Displaying decimal values with a predefined format
You can use BigDecimal
with the desired scale (e.g. 2) and rounding mode (e.g HALF_UP
) like so:
import java.math.BigDecimal
import java.math.RoundingMode
fun main() {
val roundingMode = RoundingMode.HALF_UP
val doubles: List<Double> = listOf(
-0.00123, -2.222154, -23.154, -2.13, -0.10001, -10.0012,
-1.0023, 0.23, 0.56474, 1.000, 11.1111, 1.89566
)
doubles.map { BigDecimal(it).setScale(2, roundingMode) }.also { println(it) }
// [0.00, -2.22, -23.15, -2.13, -0.10, -10.00, -1.00, 0.23, 0.56, 1.00, 11.11, 1.90]
}
Same approach in a more functional flavour (partial function instead of constants):
val fancyRound: (scale: Int, roundingMode: RoundingMode) -> (Double) -> BigDecimal =
{ scale, roundingMode ->
{ d -> BigDecimal(d).setScale(scale, roundingMode) }
}
fun main() {
...
val myRound = fancyRound(2, RoundingMode.HALF_UP)
doubles.map { myRound(it) }.also { println(it) }
}
Set n decimal places in BigDecimal and format the number Java
As mentioned by @JB Nizet, you need to tune NumberFormat acc. to your need.
Below is a working example:
int numberOfDecimalPlaces = 6;
BigDecimal bigDecimal = new BigDecimal(11212.122323);
bigDecimal.setScale(numberOfDecimalPlaces, RoundingMode.HALF_UP);
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMinimumFractionDigits(numberOfDecimalPlaces);
System.out.println(numberFormat.format(bigDecimal));
Output:
11,212.122323
Related Topics
Make Code With Firebase Asynchronous
Spritekit Physics in Swift - Ball Slides Against Wall Instead of Reflecting
What Is the Reduce() Function Doing, in Swift
Swift 2/iOS 9 - Libz.Dylib Not Found
A Swift Protocol Requirement That Can Only Be Satisfied by Using a Final Class
Using Foreach Loop with Binding Causes Index Out of Range When Array Shrinks (Swiftui)
Implicitly Unwrapped Optional Made Immutable
How to Get Indexpath When Image Inside Cell Tapped
Distinction in Swift Between Uppercase "Self" and Lowercase "Self"
Swift Sphere Combine Star Data
The "Prefs" Url Scheme Is Not Working in iOS 10 (Beta 1 & 2)
Finish Asynchronous Task in Firebase With Swift
Pull Down to Refresh Data in Swiftui
What's the Difference Between Aranchor and Anchorentity
Is There a Prefix Header (Or Something with This Functionality) in Swift