1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

QString で long double を扱う

Last updated at Posted at 2016-10-03

概要

QString は int, double 等に対応する変換のメソッドがあります(number,setNum,arg,toInt,...)。
しかし、long double はプリミティブ型にも関わらず変換メソッドが用意されていません。
こういった場合は、std::string を経由することで変換できます。

long double → QString


#include <sstream>
#include <QString>

QString to_qstring(const long double value)
{
  std::stringstream ss;
  ss << value;

  return QString::fromStdString(ss.str());
}

QString → long double


#include <sstream>
#include <QString>

long double to_long_double(const QString & str)
{
  std::stringstream ss(str.toStdString());
  long double value;
  ss >> value;

  return value;
}

補足:C++11以降の場合

C++11 以降であれば、std::stringとの変換メソッドがあります(std::to_string, std::stold)。
そのため、std::stringstream なしに変換できます。

long double → QString


#include <string>
#include <QString>

QString to_qstring(const long double value)
{
  return QString::fromStdString(std::to_string(value));
}

QString → long double


#include <string>
#include <QString>

long double to_long_double(const QString & str)
{
  return std::stold(str.toStdString());
}

参考資料

  1. c++ - long double to string - Stack Overflow
  2. C++11メモ @ std::to_stringで数値から文字列に変換 - ラーメンは味噌汁
  3. C++11メモ @ 文字列から浮動小数点値への変換 - ラーメンは味噌汁
  4. stringstream - C++ Reference
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?