我越来越认为这是一个奇数舍入的小数位。
我使用+ cast将.toFixed()返回的字符串转换为数字。
为了清晰起见,我进行了一些测试并添加了数字。我对Test 3
和123.4600
第一个测试按预期工作 - 期望向上舍入2个小数位。
然而,第三个对我来说很奇怪,它是否也应该向var module = require("../../tests/yootil/Utilities.js");
// yootil.Utilities.stringToNumber
//
describe('yootil.Utilities.stringToNumber', function(){
// TEST 1
it('Should return a number with 2 decimals', function(){
expect(module.yootil.Utilities.stringToNumber("123.4585")).toEqual(123.46);
});
// TEST 2
it('Should return a number with zero decimal places', function(){
expect(module.yootil.Utilities.stringToNumber("123.4585", 0)).toEqual(123);
});
// TEST 3
it('Should return a number with 4 decimals', function(){
expect(module.yootil.Utilities.stringToNumber("123.4587", 4)).toEqual(123.4587);
});
// TEST 4
it('Should return null with an invalid string', function(){
expect(module.yootil.Utilities.stringToNumber("test")).toEqual(null);
});
// TEST 5
it('Should return null with NO parameters', function(){
expect(module.yootil.Utilities.stringToNumber()).toEqual(null);
});
});
四舍五入?
var yootil = {};
yootil = (function(module){
module.Utilities = {
/**
* Converts a string representation of a number
* to a number with decimal places.
*
* <example>
* var yo = yootil.Utilities; // create a cached version
*
* yo.stringToNumber() // null
* yo.stringToNumber("12.3849") // 12.38
* yo.stringToNumber("123.3849", 0) // 123
* yo.stringToNumber("test") // null
* </example>
*
* @param {string} string A number string
* @param {int} Decimal places
* @return {boolean}
**/
stringToNumber: function(string, decimal_places){
try{
if(!string || isNaN(+(string))){
throw new Error('yootil.Utilities.stringToNumber expects a valid number string "123.45" )');
}
decimal_places = (decimal_places === 0) ? 0 : (decimal_places) || 2;
return +(parseFloat(string).toFixed(decimal_places));
}catch(e){ console.error(e); console.log(string); return null;}
}
}
return module;
}(yootil = yootil || {}));
exports.yootil = yootil;
#!/bin/bash
read -p "Please enter the path and filename...Example=/var/tmp/test.txt #:" location
while [[ -f ! ${location} ]] ; do
echo "File not found... Try again."
read -p "Please enter the path and filename... Example=/var/tmp/test.txt #:" location
done
chmod 755 ${location}