Как double преобразовать в string

от admin

Как double преобразовать в string

Here, we will build a C++ program for double to string conversion using various methods i.e.

  1. Using to_string
  2. Using stringstream
  3. Using sprintf
  4. Using lexical_cast

We will keep the same input in all the mentioned approaches and get an output accordingly.

Input:

Output:

1. Using to_string

In C++, use std::to string to convert a double to a string. The required parameter is a double value, and a string object containing the double value as a sequence of characters is returned.

Convert double to string in C++ – (3 ways)

In this article, we will learn about three different ways to convert a double to a string in C++ i.e.

  1. Using std::to_string() function
  2. Using std::stingstream
  3. Using Boost’s lexical_cast() function.

Let’s discuss them one by one.

Convert double to string using to_string()

C++ provides a function std::to_string() for data type conversion. We can use this to convert a double to a string. For example,

We passed a double value to the to_string() function, and it converted the given double to a string and returned the string object. It will keep the precision level as it is. If you want more control over the precision level of double while converting it to string, then look at the following technique using stringstream.

Convert double to string with specified precision using stringstream in C++

C++ provides a class stringstream, which provides a stream-like functionality. We can insert different types of elements in stringstream and get a final string object from the stream. We can use that to convert double to string. In the stream, we can also set the precision level of double-type elements before conversion. Check out this example,

Output:

Read More:

In the stringstream, we inserted a double to the stringstream, and then the stream converted the double to string. Also, as we set the precision level to 3, it rounded off the value to keep only three digits after the dot.

Convert double to string using boost::lexical_cast()

The C++ boost library, provides a template function for data type conversion. It helps to convert elements from one data type to another. We can use that to convert a double to string. For example,

Output:

Summary:

We learned about three different ways to convert a double value to a string in C++.

Related posts:

Advertisements

Thanks for reading.

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Advertisements

Advertisements

Advertisements

Advertisements

C++ – Smart Pointers

C++ Threads

C++ – STL Tutorials

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

How do I convert a double into a string in C++?

I need to store a double as a string. I know I can use printf if I wanted to display it, but I just want to store it in a string variable so that I can store it in a map later (as the value, not the key).

18 Answers 18

The boost ™ way:

The Standard C++ way:

Note: Don’t forget #include <sstream>

Johannes Schaub - litb's user avatar

The Standard C++11 way (if you don’t care about the output format):

to_string is a new library function introduced in N1803 (r0), N1982 (r1) and N2408 (r2) «Simple Numeric Access«. There are also the stod function to perform the reverse operation.

If you do want to have a different output format than «%f» , use the snprintf or ostringstream methods as illustrated in other answers.

If you use C++, avoid sprintf . It’s un-C++y and has several problems. Stringstreams are the method of choice, preferably encapsulated as in Boost.LexicalCast which can be done quite easily:

sprintf is okay, but in C++, the better, safer, and also slightly slower way of doing the conversion is with stringstream :

In both instances, str should be «453.23» afterward. LexicalCast has some advantages in that it ensures the transformation is complete. It uses stringstream s internally.

coppro's user avatar

I would look at the C++ String Toolkit Libary. Just posted a similar answer elsewhere. I have found it very fast and reliable.

The problem with lexical_cast is the inability to define precision. Normally if you are converting a double to a string, it is because you want to print it out. If the precision is too much or too little, it would affect your output.

You could also use stringstream.

Heh, I just wrote this (unrelated to this question):

Vinko Vrsalovic's user avatar

Normaly for this operations you have to use the C default ecvt, fcvt or gcvt Functions:

For the record: In my own code, I favor snprintf(). With a char array on the local stack, it’s not that inefficient. (Well, maybe if you exceeded the array size and looped to do it twice. )

(I’ve also wrapped it via vsnprintf(). But that costs me some type checking. Yelp if you want the code. )

Take a look at sprintf() and family.

Note that a string is just a representation of the double and converting it back to double may not result in the same value. Also note that the default string conversion may trim the conversion to a certain precision. In the standard C++ way, you can control the precision as follows:

which will give you the output

Erik Bongers's user avatar

Use to_string() .
example :

Hossein's user avatar

You could try a more compact style:

Zach Saucier's user avatar

Alexis Sánchez Tello's user avatar

You can convert any thing to anything using this function:

Which provide fast low level way to convert floating points into string with some level of format control. This should be fast since no allocation is done, only custom implementation for specific scenario should be faster.

C++20 has introduced high level easy to use format string (equivalent of fmt library):

Convert double to String in Java

The double data type can be converted to string in JAVA using inbuilt functions present in Java class libraries. Strings help us store larger numbers that don't fit in any data type like integer or double that stores the numbers. There are different methods to convert double numbers to strings in Java. To understand the concepts covered in the article you should have a basic knowledge of the basic data types and work of strings.

Читать:
Чем заменить антивирус avira

Scope of Article

In this article, we will explore different ways to convert the double data type to string in Java. There are several methods to perform the conversion. Let's look at each of them closely.

  • Convert double to string using valueOf()
  • Convert double to string using DecimalFormat.format()
  • Converting from double to string using StringBuffer and StringBuilder .
  • Convert double to string using toString()
  • Converting from double to String using +Operator
  • Convert double to String using format()

Introduction

The double data type can be converted to string in JAVA using inbuilt functions present in Java class libraries. It helps us store a large stream of numbers that other data types available to store large numbers fail to do. There are different inbuilt functions to convert double to string like valueOf() , toString() , DecimalFormat.format() and many others. Each of them has different use and properties.

Let's have a closer look at each of them.

Example 1: Converting from Double to String Using valueOf() Method in Java

String.valueOf() is an inbuilt method of String class in Java to convert different parameters to strings. It works with parameters like an object , float , char , double , int , long , and char[] . Since it is an inbuilt method, it is already present in the java directory which returns the string object.

Syntax:

  • String output = String.valueOf(parameter);

Parameters: object, float, char, double, int, float, long, char[]

Let's discuss it with an example:

Example 1: The following code converts the double number to a string using the String.valueOf method.

Output:

Example 2 Let's have a look at another example taking a double value as user input.

Output:

In the above example, we have converted double variable to string using the valueOf() method of the String class. Also, the valueOf() method is the most used way of converting a double variable to a string in Java.

Example 2: Java Program to Convert double to String Using DecimalFormat.format()

Java program can be converted from double to string using the DecimalFormat.format() method by importing java.text.DecimalFormat package into the code. It is used to represent double as a string with a specified number of digits after the decimal and rounded values to decimal places.

Syntax:

OR

Let's see it with an example:

Example 1: The following example specifies the decimal values of the converted number to be 3.

Output:

Example 2: The following example specifies the decimal values of the converted number to be 4 . As the digits after decimal in the original number were less than 4 , another zero digits get added to satisfy the formatting.

Output:

Example 3: The following example specifies the decimal values of the converted number to be 2 . Since the original number has 3 digits after decimal which is more than 2 , it rounds off the number to two decimal places and then converts it to string.

Output:

Example 4: The above codes can also be written in a different format as:

Output:

Example 3: Java Program to Convert double to string using StringBuffer and StringBuilder.

We can also convert double to string using both StringBuffer and StringBuilder using the same steps. It first creates an instance, then appends the double value and converts it to a string. The append method accepts a value of any data type as a parameter and adds it to the current object.

Let's explore it using an example.

Syntax:

Parameter: boolean, char, double, float, int, long, string, char[]

Example of converting double to string using StringBuffer :

In this example, we will discuss how to convert double to string using the StringBuffer object. We append a double value to the StringBuffer object using the append() method and get the string value using the toString() method.

Output:

Example of converting double to string using StringBuilder :

In this example, we will discuss how to convert double to string using the StringBuilder object. We append a double value to the StringBuilder object using the append() method and get the string value using the toString() method.

Output:

Example 4: Java Program to Convert double to string using toString()

This is another method to convert double to string using the toString() method of the double class. It stores the primitive double value to the Double class reference variable and changes it to a string using the toString() method.

Syntax:

Example 1: In the following example, we convert the primitive double value by first reading it to the double class reference variable and then converting it using the toString() method.

Output:

Example 2: The double value can also be passed directly to the toString() method or can be taken as an input from a user and passed to the reference variable. Let's have a look at it using an example.

Output:

Here, double is a wrapper class in Java that allows us to convert primitive data types into objects and object into primitive data types.

A print statement in Java always converts other data types to strings using the toString() method of Object class whether called directly or not. When a user creates an object of any type, the toString() method gets overridden so that the print command calls the overridden toString() method. If no object is created by the user, the inbuilt function present in the Java directory automatically converts the double value to string.

Example 5: Java Program To Convert double to String Using + Operator

This method uses the concatenation property of strings to convert a variable of double datatype into the string. The + sign concatenates the string to the number changing it to string type.

Syntax:

Example: The following example helps us add numbers to string. The + operator concatenates the string with the number.

Example 6: Program to Convert double to String using format() method in Java

Java program can be converted from double to string using the String.format() method. It is used to represent double as a string with a specified number of digits after the decimal and rounded values to decimal places.

Syntax:

Example 1:

Output:

Example 2: This method helps us alter the digits after the decimal in the string or round it off to specified decimal places. Let's explore it through an example.

Output:

The above code helps us adjust the number of digits after the decimal to two in the output string. This method helps us in rounding decimals.

Conclusion

Java programs automatically get converted to string at the time of printing.

Похожие статьи