将数字转换为字符串
本课属于 Coddy Dart 学习旅程的“基础知识”单元。第 85 课,共 94 课。
toString() 方法可以把数字转换为字符串。当你需要以文本形式显示数字,或将数字与其他字符串组合时,这很有用。
将整数转换为字符串:
int age = 25;
String ageText = age.toString();
print(ageText);运行以上代码后,输出将是:
25将 double 转换为字符串:
double price = 19.99;
String priceText = price.toString();
print(priceText);运行以上代码后,输出为:
19.99挑战
入门在这个挑战中,你将练习使用 Dart 中的 toString() 方法将数字转换为字符串。此方法会将数值转换为其字符串表示形式。
补全代码,将 score 变量转换为字符串,并将其存储在 scoreAsString 变量中。
预期输出:
Original score (number): 85
Converted score (string): 85
Type of converted score: String亲手试试
void main() {
// 这个数字已经为你定义好了
int score = 85;
// TODO:使用 toString() 将 score 转换为字符串
// 并将其存入 scoreAsString 变量
String scoreAsString = "";
// 这里会显示结果
print('Original score (number): $score');
print('Converted score (string): $scoreAsString');
print('Type of converted score: ${scoreAsString is String ? "String" : "Not a String"}');
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
基础知识中的所有课
自己练习: Dart 在线编译器