根据下面的模拟,温度应该有
-
小数点左侧至少 2 位
数字 -
正好是小数点右侧的 1 位数字
例如:
31.105
应该31.1
2
应该02.0
cityDetails = {
city: "chennai",
country: "india",
weather: [
{
date: "Aug 3, 2018",
temperature: 2,
weather_name: "sunny",
weather_image: "some image url"
}
]
};
下面是我尝试过的代码,
transform(cityDetails) {
this.temp = cityDetails.weather[0].temperature.toString().replace(
/d+/g,
function pad(digits) {
return digits.length === 1 ? '0' + digits : digits;
});
}
但它并没有按预期工作。链接到我的 https://stackblitz.com/edit/angular-wc8vu1
在这里看到工作闪电战: https://stackblitz.com/edit/angular-8dhh12?file=src/app/app.component.ts
transform(cityDetails) {
let pad = (digits) => digits.split('.')[0].length === 1 ? '0' + digits : digits;
this.temp = pad(cityDetails.weather[0].temperature.toFixed(1));
}
使用管道number
更好的方法是 https://stackblitz.com/edit/angular-kzkne3?file=src/app/app.component.html
{{temp | number:'2.1'}}