Double to String Conversion Without Scientific Notation

How do I print a double value without scientific notation using Java?

You could use printf() with %f:

double dexp = 12345678;
System.out.printf("dexp: %f\n", dexp);

This will print dexp: 12345678.000000. If you don't want the fractional part, use

System.out.printf("dexp: %.0f\n", dexp);

0 in %.0f means 0 places in fractional part i.e no fractional part. If you want to print fractional part with desired number of decimal places then instead of 0 just provide the number like this %.8f. By default fractional part is printed up to 6 decimal places.

This uses the format specifier language explained in the documentation.

The default toString() format used in your original code is spelled out here.

Formatting A Double In A String Without Scientific Notation

Use just %f instead of %.0f.

import java.math.BigDecimal;

public class Main {
public static void main(String[] args) {
double foo = 123456789.1234;
String str = String.format("%f", foo);
System.out.println(str);

// If you want to get rid of the trailing zeros
str = new BigDecimal(str).stripTrailingZeros().toString();
System.out.println(str);
}
}

Output:

123456789.123400
123456789.1234

Double to string conversion without scientific notation

For a general-purpose¹ solution you need to preserve 339 places:

doubleValue.ToString("0." + new string('#', 339))

The maximum number of non-zero decimal digits is 16. 15 are on the right side of the decimal point. The exponent can move those 15 digits a maximum of 324 places to the right. (See the range and precision.)

It works for double.Epsilon, double.MinValue, double.MaxValue, and anything in between.

The performance will be much greater than the regex/string manipulation solutions since all formatting and string work is done in one pass by unmanaged CLR code. Also, the code is much simpler to prove correct.

For ease of use and even better performance, make it a constant:

public static class FormatStrings
{
public const string DoubleFixedPoint = "0.###################################################################################################################################################################################################################################################################################################################################################";
}

¹ Update: I mistakenly said that this was also a lossless solution. In fact it is not, since ToString does its normal display rounding for all formats except r. Live example. Thanks, @Loathing! Please see Lothing’s answer if you need the ability to roundtrip in fixed point notation (i.e, if you’re using .ToString("r") today).

Convert string to double without scientific notation

The methods you have used do not return 1.08595E8, instead, they return the number and what you are complaining about is the representation of that number in the console (or as a String).

However, you can specify how to output a doubleyourself with a specified formatting, see this example:

public static void main(String[] args) {
String value = "108595000.5";
// use a BigDecimal to parse the value
BigDecimal bd = new BigDecimal(value);
// choose your desired output:
// either the String representation of a double (undesired)
System.out.println("double:\t\t\t\t\t" + bd.doubleValue());
// or an engineering String
System.out.println("engineering:\t\t\t\t" + bd.toEngineeringString());
// or a plain String (might look equal to the engineering String)
System.out.println("plain:\t\t\t\t\t" + bd.toPlainString());
// or you specify an amount of decimals plus a rounding mode yourself
System.out.println("rounded with fix decimal places:\t"
+ bd.setScale(2, BigDecimal.ROUND_HALF_UP));
}
double:                             1.085950005E8
engineering: 108595000.5
plain: 108595000.5
rounded with fix decimal places: 108595000.50

Convert long double to string without scientific notation (Dart)

There is no easy way to do what you want directly with the Dart platform libraries, mainly because there is no way to do it in JavaScript.

You can use num.toStringAsFixed(20), but that is limited to 20 digits, and your number needs 23.

One thing you could do is to manipulate the string directly:

String toExact(double value) {
var sign = "";
if (value < 0) {
value = -value;
sign = "-";
}
var string = value.toString();
var e = string.lastIndexOf('e');
if (e < 0) return "$sign$string";
assert(string.indexOf('.') == 1);
var offset = int.parse(string.substring(e + (string.startsWith('-', e + 1) ? 1 : 2)));
var digits = string.substring(0, 1) + string.substring(2, e);
if (offset < 0) {
return "${sign}0.${"0" * ~offset}$digits";
}
if (offset > 0) {
if (offset >= digits.length) return sign + digits.padRight(offset + 1, "0");
return "$sign${digits.substring(0, offset + 1)}"
".${digits.substring(offset + 1)}";
}
return digits;
}

Do notice that you can't necessarily get the value as written because not all double values are exact. In this particular case, you seem to be be fine.

Conversion of string to double without scientific notation in C++

The scientific notation has to do with std::cout, not the way the value is stored, so you must use std::fixed before you print the value:

std::cout << std::fixed << std::setprecision(2) << d << std::endl;

As you can see in the demo, this works fine, it should work for you as well.

As @goodvibration commented std::to_string also works but it's not possible to redefine, in a simple manner, the default number or decimal places in this case.

std::cout << std::to_string(d) << std::endl;

Live demo

How to avoid scientific notation when converting small double values to string?

If you don't have a numeric source for that data and you actually need to parse the content of UI elements, the Culture used when inserting data matters, because not all cultures use a comma as decimal separator: if the current UI Culture (Thread.CurrentThread.CurrentCulture and Thread.CurrentThread.CurrentUICulture) don't match the input format (you show input that uses a comma instead of a dot - as the InvariantCulture - to separate the decimal part), then the text will not parse correctly or at all.

If you have a text input that uses a specific culture format, you need to parse that input specifying the corresponding CultureInfo.

Numbers don't have a format: if you have a numeric source, use that for the calculations, then present the data using the destination UI Culture to provide a localized representation of those value.

If the input Culture and the current Culture are the same, then you don't need to specify a CultureInfo when parsing string values, since the Culture returned by Thread.CurrentThread.CurrentCulture is used.


Assuming that the input format is based on the Italian format for decimal numbers (assumption based on the use of the name PREZZO, which Google Translate detects as Italian), you can create a CultureInfo that provides standard formats used in that culture.

When parsing the string values, pass this CultureInfo to the methods, so the text will be parsed correctly.

Also, since you dealing with currency, don't use Double or CDbl to parse those values, use Decimal.Parse() instead. For example:

Dim PREZZO = "0,04831"
Dim currentPrice = Label16.Text ' "0,04840"

Dim culture = CultureInfo.CreateSpecificCulture("it-IT")

Dim price = Decimal.Parse(PREZZO, culture)
Dim price1Year = Decimal.Parse(currentPrice, culture)
Dim priceDiff = price1Year - price
Dim priceDiffPercent = priceDiff / price

Now, to present the calculated variation in price and the percentage of the variation, you need to format back those values using the same CultureInfo:

labelDiffPrice.Text = priceDiff.ToString("N5", culture)
labelDiffCurrency.Text = priceDiff.ToString("C5", culture)
labelDiffPercent.Text = priceDiffPercent.ToString("P5", culture)

N5 specifies a number with a precision of 5 decimal values.

C5 species to use Currency format and Symbol defined by the CultureInfo, with a precision of 5 decimal values. This overrides the CultureInfo.NumberFormat.CurrencyDecimalDigits, so it should be used for a specific purpose, as in this case.

P5 a percentage representation of a number multiplied by 100 with a precision of 5 decimal positions.

The two calculated values will be presented as:

 ' Variation in price
0,00009

' Variation in price expressed in currency
€ 0,00009

' Percentage of the variation
0,18630%

If the input comes directly from a User, use Decimal.TryParse() instead of Decimal.Parse() to validate the input.

See also: Standard numeric format strings

Java Double to String conversion without formatting

Use Long:

long id = 654987;
String str = Long.toString(id);


Related Topics



Leave a reply



Submit